java - 如何将秒四舍五入到十分位?

标签 java

我认为通过将值转换为 float ,它将显示秒到十分之一。

long startTime = System.currentTimeMillis();

    while (RUNNING) {
        track.repaint();
        // varying the x position movement
        horse.setX(xpos += (int) (Math.random() * 10 + 0));
        // Sleeping the thread
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (xpos >= FINISH_LINE) {              
            RUNNING = false;
            long endTime = System.currentTimeMillis();
            JOptionPane.showMessageDialog(new JFrame(), id + " Won and took " +(float)(startTime - endTime)/1000*-1.0+ " seconds");             
        }

    }

相反,它给了我太多的精确度。我想把它剪掉一点。

最佳答案

很简单!使用DecimalFormat:

JOptionPane.showMessageDialog(new JFrame(), id + " Won and took " + new DecimalFormat(".##").format((float)(startTime - endTime)/1000*-1.0)+ " seconds");

关于java - 如何将秒四舍五入到十分位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22888008/

相关文章:

java - 配置单元 Metastore 和连接拒绝进入配置单元外壳的错误

java - 将多个项目添加到链接列表中

java - HashSet 不会拒绝第二次添加调用

java - 在 SWT 程序中,如何启动一个能够在不阻塞的情况下更新 UI 的线程

java - 具有不同契约(Contract)的装饰器模式

java - GAE - 如何进行 XML-RPC 调用?

java - 如何将一个值赋给多个变量

Java DateTimeFormatter.ISO_OFFSET_DATE_TIME 输出与 Java 文档不同

java - 从 apache FileUtils 获取过滤后的文件列表

java - 如何在 vaadin 中格式化表值?