Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying floating-point number as a percentage without changing the value of the number

Is it possible to specify string.Format() parameters to add percentage symbol without changing the value of the number?

Example:
We have the number 44.36 and we want to show in a grid and output to Excel as "44.36%". Dividing the value by 100 and then apply the "P" format is not an option. Changing the values can not be done in this case, we need to do it only by changing the DisplayFormat value. Using string.Format("{0}%", valueParam) is not an option either.

like image 939
Lonli-Lokli Avatar asked Feb 21 '11 20:02

Lonli-Lokli


1 Answers

Specify a custom format. You'll need to escape the percent sign '%' with a literal backslash '\\' so it doesn't reinterpret the value as a percentage.

var number = 44.36m;
var formatted = number.ToString("0.##\\%"); // "44.36%"
// format string @"0.##\%" works too

// using String.Format()
var sformatted = String.Format("{0:0.##\\%}", number); // "44.36%"
like image 54
Jeff Mercado Avatar answered Sep 17 '22 18:09

Jeff Mercado