开发者

Round decimal digits to upper value

开发者 https://www.devze.com 2023-04-04 21:14 出处:网络
I want to round decimal value digits to upper value if digit isn\'t zero. I want to round the 6th digit to upper value .

I want to round decimal value digits to upper value if digit isn't zero. I want to round the 6th digit to upper value .

Sample Value    =开发者_开发百科 1.0003331
Expected Value  = 1.000334


Sounds like you might want:

decimal scale = 1000000m;
decimal rounded = decimal.Ceiling(x * scale) / scale;

(The scale may be off by one :)

Obviously this will cause a problem if you try to handle very large numbers with it - they could overflow.

I'd like to think you could also do the same thing by adding a certain amount and then using decimal.Round, but it's slightly awkward without a MidpointRounding of RoundTowardsZero.


You can try something like this:

decimal.Round(Value + 0.00000049m, 6, MidpointRounding.AwayFromZero)

MidpointRounding.AwayFromZero ensure that when a number is halfway between two others, it is rounded toward the nearest number that is away from zero.

MSDN Decimal.Round

0

精彩评论

暂无评论...
验证码 换一张
取 消