How to convert milliseconds to seconds with precision

余生颓废 提交于 2019-11-29 10:52:04

问题


I want to convert milliseconds to seconds (for example 1500ms to 1.5s, or 500ms to 0.5s) with as much precision as possible.

Double.parseDouble(500 / 1000 + "." + 500 % 1000); isn't the best way to do it: I'm looking for a way to get the remainder from a division operation so I could simply add the remainder on.


回答1:


Surely you just need:

double seconds = milliseconds / 1000.0;

There's no need to manually do the two parts separately - you just need floating point arithmetic, which the use of 1000.0 (as a double literal) forces. (I'm assuming your milliseconds value is an integer of some form.)

Note that as usual with double, you may not be able to represent the result exactly. Consider using BigDecimal if you want to represent 100ms as 0.1 seconds exactly. (Given that it's a physical quantity, and the 100ms wouldn't be exact in the first place, a double is probably appropriate, but...)




回答2:


Why don't you simply try

System.out.println(1500/1000.0);
System.out.println(500/1000.0);



回答3:


I had this problem too, somehow my code did not present the exact values but rounded the number in seconds to 0.0 (if milliseconds was under 1 second). What helped me out is adding the decimal to the division value.

double time_seconds = time_milliseconds / 1000.0;   // add the decimal
System.out.println(time_milliseconds);              // Now this should give you the right value.


来源:https://stackoverflow.com/questions/14090898/how-to-convert-milliseconds-to-seconds-with-precision

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!