简体   繁体   English

以百分比形式显示浮点数而不更改数字的值

[英]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? 是否可以指定string.Format()参数来添加百分比符号而不更改数字的值?

Example: 例:
We have the number 44.36 and we want to show in a grid and output to Excel as "44.36%" . 我们有44.36号码,我们想要在网格中显示并输出到Excel为"44.36%" Dividing the value by 100 and then apply the "P" format is not an option. 将值除以100然后应用"P"格式不是一种选择。 Changing the values can not be done in this case, we need to do it only by changing the DisplayFormat value. 在这种情况下无法更改值,我们只需要通过更改DisplayFormat值来完成。 Using string.Format("{0}%", valueParam) is not an option either. 使用string.Format("{0}%", valueParam)也不是一个选项。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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