This question already has answers here:
Java decimal formatting using String.format?
                                
                                    (6个答案)
                                
                        
                                5年前关闭。
            
                    
我认为通过将值强制转换为浮点数可以将秒数显示为十分之一。

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");

07-25 22:12