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

后端 未结 3 364
渐次进展
渐次进展 2020-12-31 05:10

Update

OK, after some investigation, and thanks in big part to the helpful answers provided by Jon and Hans, this is what I was able to put together. So far I thin

相关标签:
3条回答
  • 2020-12-31 05:50

    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.

    0 讨论(0)
  • 2020-12-31 05:50

    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.

    0 讨论(0)
  • 2020-12-31 05:50

    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.

    0 讨论(0)
提交回复
热议问题