Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert milliseconds to seconds with precision

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.

like image 266
Keir Nellyer Avatar asked Dec 30 '12 12:12

Keir Nellyer


People also ask

How do you convert milliseconds ms into seconds?

To convert a millisecond measurement to a second measurement, divide the time by the conversion ratio. The time in seconds is equal to the milliseconds divided by 1,000.

How do you convert milliseconds into hours minutes and seconds?

To convert milliseconds to hours, minutes, seconds:Divide the milliseconds by 1000 to get the seconds. Divide the seconds by 60 to get the minutes. Divide the minutes by 60 to get the hours. Add a leading zero if the values are less than 10 to format them consistently.

How do you convert milliseconds?

To convert a second measurement to a millisecond measurement, multiply the time by the conversion ratio. The time in milliseconds is equal to the seconds multiplied by 1,000.

How much is a 1 millisecond?

A millisecond (from milli- and second; symbol: ms) is a unit of time in the International System of Units (SI) equal to one thousandth (0.001 or 10−3 or 1/1000) of a second and to 1000 microseconds.


2 Answers

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...)

like image 101
Jon Skeet Avatar answered Sep 20 '22 08:09

Jon Skeet


Why don't you simply try

System.out.println(1500/1000.0); System.out.println(500/1000.0); 
like image 37
Ankur Avatar answered Sep 22 '22 08:09

Ankur