iKeirNez - 15 days ago 6

Java Question

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

Answer

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

Source (Stackoverflow)

Comments