将指数转换为十进制1.11111117E + 9-尾随数字变为零 [英] Converting exponential number to decimal 1.11111117E+9 - trailing digits become zero

查看:260
本文介绍了将指数转换为十进制1.11111117E + 9-尾随数字变为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试转换和指数编号1.11111117E + 9,它实际上是10位数字'1111111111'.当我尝试使用decimal.TryParse方法转换此指数时,它会将最后3位数字设为零,并将数字指定为" 111111000 ".任何10位数字都会发生这种情况.

I'm trying to convert and exponential number 1.11111117E+9 which is actually a 10 digit number '1111111111'. When I'm trying to convert this exponential number using decimal.TryParse method it is making last 3 digits as zero and giving the number as '111111000'. This is happening with any 10 digit number.

   decimal amount;
   decimal.TryParse("1.11111117E+9", NumberStyles.Any, null, out amount);

这很奇怪,但是我无法弄清楚这里出了什么问题,有人可以告诉我这是怎么回事吗?

This is weird but I'm not able to figure out what's the issue here, can anybody tell me what's wrong in this?

修改: 对误导性问题深表歉意.正如 Henrik 在他的回答中提到的,这正是我所面临的.

Sorry for the misleading question. As Henrik mentioned in his answer is exactly what I'm facing.

float f = 1111111111;
string s = f.ToString();
decimal amount;
decimal.TryParse(s, NumberStyles.Any, null, out amount);

这将始终返回1111111000吗?如何解决此问题以获得正确的值?将其从float数据类型更改为Double或Decimal是解决方案还是其他任何方法?

This will always return 1111111000? How do I address this issue to get the correct value? Change it to Double or Decimal from float datatype is the solution or anything else?

推荐答案

往返浮点数很容易...

It's easy to round-trip a float value...

float f = 1111111111;
string s = f.ToString("r"); // r = roundtrip
float g = float.Parse(s);

现在fg将相同...但这并不意味着两个值都恰好是1111111111 ...因为该值不能表示为浮点数.可以精确表示为浮点数的最接近值是1111111168 ...这就是为什么在科学表示法的末尾得到7的原因.

Now f and g will be the same... but that doesn't mean that either value is exactly 1111111111... because that value can't be represented as a float. The nearest value exactly representable as a float is 1111111168... which is why you're getting the 7 at the end of the scientific representation.

基本上,您不应该首先使用float.从 System.Single 的文档中:

Basically, you shouldn't be using float for this in the first place. From the docs for System.Single:

默认情况下,单个"值仅包含7个精度的十进制数字,尽管内部最多保留9个数字.

By default, a Single value contains only 7 decimal digits of precision, although a maximum of 9 digits is maintained internally.

因此,试图存储10位数字并期望将其准确存储是一个傻瓜的事情.

So trying to store a 10 digit number and expecting it to be stored exactly is a fool's errand.

很难说您应该使用double还是decimal-这取决于您实际上要存储的值.如果它是自然"的值(例如体重或身高),我会选择double.如果它是像价格一样的人类"价值,我会使用decimal.

It's hard to say whether you should be using double or decimal - it depends on what value you're really trying to store. If it's a "natural" value like weight or height, I'd go for double. If it's a "human" value like a price, I'd use decimal.

这篇关于将指数转换为十进制1.11111117E + 9-尾随数字变为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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