将 float 转换为 double 而不会丢失精度

时间:2022-11-07
本文介绍了将 float 转换为 double 而不会丢失精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个原始浮点数,我需要一个原始双精度数.简单地将浮点数转换为 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

有没有更好的方法而不是去字符串然后返回?

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.

当您转换为字符串并返回时,您最终会得到一个比原始浮点数更接近字符串值的双精度值 - 但这只是 如果 你真的相信字符串值是您真正想要的.

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.

这篇关于将 float 转换为 double 而不会丢失精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一条:Java中的浮点和双精度数据类型 下一条:将浮点数格式化为 n 位小数

相关文章

最新文章