Home > Back-end >  Correct string formatting (or rounding)
Correct string formatting (or rounding)

Time:03-23

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?

CodePudding user response:

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 %"
  • Related