'Correct string formatting (or rounding)

var rounded = Math.Round(value, 1);
string prob = string.Format("{0:P}", rounded);

Example:

value : 0.599..
rounded: 0.6
prob : 60.00 %

I want the prob to be just 60 % How can I do this?



Solution 1:[1]

Use {0:0%} if you want "60%" without a space between the number and percent symbol.

Use {0:P0} if you want "60 %" with a space.

var value = 0.599;
var rounded = Math.Round(value, 1);

string prob1 = string.Format("{0:0%}", rounded);
Console.WriteLine(prob1);
// prints "60%"

string prob2 = string.Format("{0:P0}", rounded);
Console.WriteLine(prob2);
// prints "60 %"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1