Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

math - How to round up or down in C#?

I have tried using Math.Round & MidpointRounding. This does not appear to do what I need.

Example:

52.34567 rounded to 2 decimals UP   = 52.35  
 1.183   rounded to 2 decimals DOWN =  1.18

Do I need to write a custom function?

Edit:

I should have been more specific.

Sometimes I need a number like 23.567 to round DOWN to 23.56. In this scenario...

Math.Round(dec, 2, MidpointRounding.AwayFromZero) gives 23.57
Math.Round(dec, 2, MidpointRounding.ToEven) gives 23.57

Decimals up to 9 decimal places could come out and need to be rounded to 1, 2, 3 or even 4 decimal places.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try using decimal.Round():

decimal.Round(x, 2)

Where x is your value and 2 is the number of decimals you wish to keep.

You can also specify whether .5 rounds up or down by passing third parameter:

decimal.Round(x, 2, MidpointRounding.AwayFromZero);

EDIT:

In light of the new requirement (i.e. that numbers are sometimes rounded down despite being greater than "halfway" to the next interval), you can try:

var pow = Math.Pow(10, numDigits);
var truncated = Math.Truncate(x*pow) / pow;

Truncate() lops off the non-integer portion of the decimal. Note that numDigits above should be how many digits you want to KEEP, not the total number of decimals, etc.

Finally, if you want to force a round up (truncation really is a forced round-down), you would just add 1 to the result of the Truncate() call before dividing again.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...