简体   繁体   English

在特定的十进制数中舍入小数java

[英]Rounding off decimals at a particular decimal number java

How to get correct time when subtracting decimal numbers.十进制数相减时如何得到正确的时间。 I wanted to subtract numbers as if it were tiime.我想减去数字,就好像它是时间一样。 But time only goes to 60 minutes whereas numbers to 100. How could I put some sort of restriction on the decimal places to make it like time.但是时间只有 60 分钟,而数字是 100。我怎么能对小数位进行某种限制,使它像时间一样。

Here's one way.这是一种方法。 The elapsed time is in milliseconds, as that is what you have when you subtract a start System.currentTimeMillis() from a finish System.currentTimeMillis().经过的时间以毫秒为单位,因为这是从结束 System.currentTimeMillis() 减去开始 System.currentTimeMillis() 时所拥有的时间。

public String formatElapsedTime(long elapsedTime) {
    int centiseconds = (int) (((elapsedTime % 1000L) + 5L) / 10L);
    centiseconds %= 10;
    int seconds = (int) (elapsedTime / 1000L);
    int minutes = seconds / 60;
    seconds -= minutes * 60;
    int hours = minutes / 60;
    minutes -= hours * 60;

    if (hours > 0) {
        return String.format("%2d:%02d:%02d.%02d", hours, minutes, seconds,
                centiseconds);
    } else if (minutes > 0) {
        return String.format("%2d:%02d.%02d", minutes, seconds,
                centiseconds);
    } else {
        return String.format("%2d.%02d", seconds, centiseconds);
    }
}

You probably don't need to display centiseconds when you're measuring elapsed time in hours.当您以小时为单位测量经过的时间时,您可能不需要显示厘秒。

Because my format strings start with “%2d”, seconds, minutes, and hours less than 10 have a space as the first character of the string.因为我的格式字符串以“%2d”开头,所以小于 10 的秒、分和小时将空格作为字符串的第一个字符。 I find this keeps the display from jumping so much.我发现这可以防止显示跳得太厉害。 If you don't want the leading space, change the format String to “%1d”.如果不需要前导空格,请将格式字符串更改为“%1d”。

You can calculate days as well, for really long elapsed times.您也可以计算天数,时间真的很长。 You would probably want a format like “3 days, 6 hours, 25 minutes, and 13 seconds”.您可能需要类似“3 天 6 小时 25 分 13 秒”的格式。 Or not.或不。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM