开发者

How to Make Math.Round for a Number

how to make the R开发者_JAVA百科ounded number ?

Example : 3341.48 to 3342.00


It seems you always want to round up here. In that case use

Math.Ceiling(3341.48)

This will return 3342.

If you want to round towards the nearest whole number, use

Math.Round(3341.48)

This will return 3341. Note that Bankers roundingis the default setting here, that might cause some unexpected result for rounding X.50.


If you want 3341.48 to round up to 3342, it sounds like you might want Math.Ceiling:

decimal m = 3341.48m;
decimal roundedUp = Math.Ceiling(m);

This will always round up - so 3341.0000001 would still round to 3342, for example. If that's not what you're after, please specify the circumstances in which you want it to round up, and those in which you want it to round down instead.

Note that this will round up to 3342, not 3342.00 - it doesn't preserve the original precision, because you've asked for an integer value by using Math.Ceiling.

It's relatively unusual to then want to force the precision to 2, but you could divide by 100 and then multiply by 100 again, if necessary. Alternatively, if you only need this for output you should look into formatting the result appropriately rather than changing the value.


Use Math.Round(number) if you want to round number to the nearest integer. Use Math.Round(number,digits) if you want to round number to a specified number of fractional digits. If you want to round to lower/higer value use Math.Floor(number) / Math.Ceiling(number) instead.


To round monetary amounts to 5 cents:

amount = 20 * int(amount / 20)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜