开发者

Round Double To Two Decimal Places [duplicate]

开发者 https://www.devze.com 2023-01-13 13:20 出处:网络
This question already has answers here: Closed 10 years ago. Possible Duplicate: c# - How do 开发者_运维问答I round a decimal value to 2 decimal places (for output on a page)
This question already has answers here: Closed 10 years ago.

Possible Duplicate:

c# - How do 开发者_运维问答I round a decimal value to 2 decimal places (for output on a page)

What is the best way to round a double to two decimal places and also have it fixed at 2 decimal places?

Example: 2.346 -> 2.35, 2 -> 2.00

I am hoping to avoid something like this where I have to convert a double to string and then back to a double which seems like a bad way to go about this.


double someValue = 2.346;    
String.Format("{0:0.00}", someValue);


Round the value to the desired precision, and then format it. Always prefer the version of Math.Round containing the mid-point rounding param. This param specify how to handle mid-point values (5) as last digit.

If you don't specify AwayFromZero as the value for param, you'll get the default behaviour, which is ToEven. For example, using ToEven as rounding method, you get:

Math.Round(2.025,2)==2.02 and

Math.Round(2.035,2)==2.04

instead, using MidPoint.AwayFromZero param:

Math.Round(2.025,2,MidpointRounding.AwayFromZero)==2.03 and

Math.Round(2.035,2,MidpointRounding.AwayFromZero)==2.04

So, for a normal rounding, it's best to use this code:

var value=2.346;
var result = Math.Round(value, 2, MidpointRounding.AwayFromZero);
var str=String.Format("{0:0.00}", result );


double someValue = 2.346;    
string displayString = someValue.ToString("0.00");

Note that double.ToString (and therefore string.Format()) uses midpoint rounding away from zero, so 0.125 becomes 0.13. This is usually the desired behavior for display. These strings should obviously not be used for round-tripping.

This method is also inappropriate for rounding that is required in mathematical calculations (where MidpointRounding.ToEven is usually the best approach). In that case, Math.Round() should be used.


Take a look at Math.Round

0

精彩评论

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