Is there a way to get the “significant figures” of a decimal?

♀尐吖头ヾ 提交于 2019-11-30 08:30:45

You can use Decimal.GetBits to get the raw data, and work it out from that.

Unfortunately I don't have time to write sample code at the moment - and you'll probably want to use BigInteger for some of the manipulation, if you're using .NET 4 - but hopefully this will get you going. Just working out the precision and then calling Math.Round on the original result may well be a good start.

Hans Passant

Yes, unlike floating point types, System.Decimal keeps track of the number of digits in the literal. This is a feature of decimal.Parse(), whether executed by your code yourself or by the compiler when it parses a literal in your program. You can recover this information, check out the code in my answer in this thread.

Recovering the number of significant digits after you do math on the value strikes me as a long shot. No idea if the operators preserve them, please let us know what you find out.

The solution above falls out of bed quickly with values like 1200 where the number of significant digits is 2 but the function returns 4. Perhaps there is a consistent manner to deal with such a situation i.e. check to make sure return value does not include trailing zeros in the whole number portion without a fractional part.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!