简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM