如何精确地将毫秒转换为秒 [英] How to convert milliseconds to seconds with precision

查看:209
本文介绍了如何精确地将毫秒转换为秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将毫秒转换为秒(例如1500ms至1.5s,或500ms至0.5s),并尽可能精确。

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); 不是最好的方法:我正在寻找一种方法来从一个部门获得剩余部分操作,所以我可以简单地添加余数。

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.

推荐答案

当然你只需要:

double seconds = milliseconds / 1000.0;

没有必要单独手动完成这两个部分 - 你只需要浮点运算,使用哪个 1000.0 (作为 double 文字)强制。 (我假设您的毫秒值是某种形式的整数。)

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

请注意,与往常一样 double ,您可能无法准确表示结果。如果要将100毫秒表示为0.1秒完全,请考虑使用 BigDecimal 。 (鉴于它是物理量,并且首先不是100毫秒, double 可能是合适的,但是......)

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

这篇关于如何精确地将毫秒转换为秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆