将浮点数转换为双倍,而不会损失精度 [英] Convert float to double without losing precision

查看:200
本文介绍了将浮点数转换为双倍,而不会损失精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个原始的浮动,我需要一个原始的双重。简单地将浮动物投射到双倍,给我奇怪的额外的精度。例如:

  float temp = 14009.35F; 
System.out.println(Float.toString(temp)); // Prints 14009.35
System.out.println(Double.toString((double)temp)); //打印14009.349609375

但是,如果代替转换,我将float作为字符串输出,并解析该字符串为双,我得到我想要的:

  System.out.println(Double.toString(Double.parseDouble Float.toString(TEMP)))); 
//打印14009.35

有没有比String更好的方法?

解决方案

这不是你实际获得额外的精度 - 这是浮动没有准确地代表你原本打算的号码。双重 正好代表原始浮标; toString 正在显示已经存在的额外数据。



例如(这些数字不是对,我只是做的事情)支持你有:

  float f = 0.1F; 
double d = f;

然后, f 的值可能正好0.100000234523。 d 将具有完全相同的值,但是当您将其转换为字符串时,它将信任准确到更高的精度,因此不会像早期,你会看到已经在那里的额外的数字,但隐藏了你。



当你转换成一个字符串并返回时,你结束了一个比原始浮点数更接近字符串值的双精度值,但这只是很好的如果你真的相信字符串值是你真正想要的。



你确定float / double是这里使用的适当类型,而不是 BigDecimal ?如果您尝试使用具有精确十进制值(例如金钱)的数字,则 BigDecimal 是一种更合适的类型IMO。


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?

解决方案

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) support you had:

float f = 0.1F;
double d = f;

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.

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.

这篇关于将浮点数转换为双倍,而不会损失精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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