[英]How to convert seconds in Double to two int's for seconds and milliseconds?
[英]How to convert milliseconds to seconds with precision
我希望尽可能精确地将毫秒转换为秒(例如1500ms至1.5s,或500ms至0.5s)。
Double.parseDouble(500 / 1000 + "." + 500 % 1000);
这不是最好的方法:我正在寻找一种方法来从除法运算中得到余数,所以我可以简单地添加余数。
当然你只需要:
double seconds = milliseconds / 1000.0;
没有必要单独手动执行这两个部分 - 您只需要浮点运算,使用1000.0
(作为double
字面值)强制。 (我假设你的milliseconds
值是某种形式的整数。)
请注意,与double
,您可能无法准确表示结果。 如果要将100毫秒精确表示为0.1秒,请考虑使用BigDecimal
。 (鉴于它是一个物理量,并且首先不是100毫秒, double
可能是合适的,但......)
你为什么不试试呢?
System.out.println(1500/1000.0);
System.out.println(500/1000.0);
我也有这个问题,不知怎的,我的代码没有提供确切的值,但是以秒为单位将数字舍入为0.0(如果毫秒不到1秒)。 帮助我的是将小数加到除法值。
double time_seconds = time_milliseconds / 1000.0; // add the decimal
System.out.println(time_milliseconds); // Now this should give you the right value.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.