问题描述
我有一个原始浮点数,我需要一个原始双精度数.简单地将 float 转换为 double 会给我带来奇怪的额外精度.例如:
I have a primitive float and I need as a primitive double. Simply casting the float to double gives me weird extra precision. For example:
float temp = 14009.35F;
System.out.println(Float.toString(temp)); // Prints 14009.35
System.out.println(Double.toString((double)temp)); // Prints 14009.349609375
但是,如果不是强制转换,而是将浮点数作为字符串输出,并将字符串解析为双精度数,我会得到我想要的:
However, if instead of casting, I output the float as a string, and parse the string as a double, I get what I want:
System.out.println(Double.toString(Double.parseDouble(Float.toString(temp))));
// Prints 14009.35
有没有比去 String 和返回更好的方法?
Is there a better way than to go to String and back?
推荐答案
这并不是说您实际上获得了额外的精度 - 而是浮点数没有准确表示您想要的数字起初.double is 准确地表示原始浮点数;toString
显示已经存在的额外"数据.
It's not that you're actually getting extra precision - it's that the float didn't accurately represent the number you were aiming for originally. The double is representing the original float accurately; toString
is showing the "extra" data which was already present.
例如(这些数字不正确,我只是在编造)假设您有:
For example (and these numbers aren't right, I'm just making things up) suppose you had:
float f = 0.1F;
double d = f;
那么 f
的值可能正好是 0.100000234523.d
将具有完全相同的值,但是当您将其转换为字符串时,它会相信"它准确到更高的精度,因此不会尽早四舍五入,您会看到已经存在但对您隐藏的额外数字".
Then the value of f
might be exactly 0.100000234523. d
will have exactly the same value, but when you convert it to a string it will "trust" that it's accurate to a higher precision, so won't round off as early, and you'll see the "extra digits" which were already there, but hidden from you.
当您转换为字符串并返回时,您最终会得到一个 double 值,该值比原始浮点数更接近字符串值 - 但这只有 如果您真的相信字符串值正是您真正想要的.
When you convert to a string and back, you're ending up with a double value which is closer to the string value than the original float was - but that's only good if you really believe that the string value is what you really wanted.
您确定 float/double 是此处使用的合适类型,而不是 BigDecimal
?如果您尝试使用具有精确十进制值的数字(例如货币),则 BigDecimal
是更合适的 IMO 类型.
Are you sure that float/double are the appropriate types to use here instead of BigDecimal
? If you're trying to use numbers which have precise decimal values (e.g. money), then BigDecimal
is a more appropriate type IMO.
这篇关于在不损失精度的情况下将浮点数转换为双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!