Round double in two decimal places in C#?

2019-01-16 03:10发布

I want to round up double value in two decimal places in c# how can i do that?

double inputValue = 48.485;

after round up

inputValue = 48.49;

Related: c# - How do I round a decimal value to 2 decimal places (for output on a page)

6条回答
三岁会撩人
2楼-- · 2019-01-16 03:26

You should use

inputvalue=Math.Round(inputValue, 2, MidpointRounding.AwayFromZero)

Math.Round

Math.Round rounds a double-precision floating-point value to a specified number of fractional digits.

MidpointRounding

Specifies how mathematical rounding methods should process a number that is midway between two numbers.

Basically the function above will take your inputvalue and round it to 2 (or whichever number you specify) decimal places. With MidpointRounding.AwayFromZero when a number is halfway between two others, it is rounded toward the nearest number that is away from zero. There is also another option you can use that rounds towards the nearest even number.

查看更多
欢心
3楼-- · 2019-01-16 03:36

Use Math.Round

value = Math.Round(48.485, 2);
查看更多
Rolldiameter
4楼-- · 2019-01-16 03:37

This works:

inputValue = Math.Round(inputValue, 2);
查看更多
地球回转人心会变
5楼-- · 2019-01-16 03:37
Math.Round(inputValue, 2, MidpointRounding.AwayFromZero)
查看更多
▲ chillily
6楼-- · 2019-01-16 03:38

Another easy way is to use ToString with a parameter. Example:

float d = 54.9700F;    
string s = d.ToString("N2");
Console.WriteLine(s);

Result:

54.97
查看更多
你好瞎i
7楼-- · 2019-01-16 03:44

you can try one from below.there are many way for this.

1. 
 value=Math.Round(123.4567, 2, MidpointRounding.AwayFromZero) //"123.46"
2.
 inputvalue=Math.Round(123.4567, 2)  //"123.46"
3. 
 String.Format("{0:0.00}", 123.4567);      // "123.46"
4. 
string.Format("{0:F2}", 123.456789);     //123.46
string.Format("{0:F3}", 123.456789);     //123.457
string.Format("{0:F4}", 123.456789);     //123.4568
查看更多
登录 后发表回答