[英]C# String format: escape a dot
I have a line of code, something like: 我有一行代码,如:
mbar.HealthLabel.text = String.Format("{0:0.0}", _hp);
Output is: 2.25 for example. 输出为:例如2.25。 Is it possible to escape a dot from the output string view with String.Format function ? 是否可以使用String.Format函数从输出字符串视图中转义一个点?
For. 对于。 ex. 恩。 225, 225,
To make my question more clear, I need the same effect like: 为了使我的问题更清楚,我需要同样的效果,如:
Math.Floor(_hp * 100).ToString();
But need to do it by String.Format
template.. Thanks. 但需要通过String.Format
模板来做..谢谢。
Simply you can do it this way 你可以这样做
double value = 1.25;
var stringValue = string.Format("{0:0}", value * 100, CultureInfo.InvariantCulture); //125
EDIT: More general solution would be to Replace
the dot with empty string as stated in the comments. 编辑:更一般的解决方案是Replace
注释中所述的空字符串Replace
点。
double value = 1.25;
var stringValue = value.ToString(CultureInfo.InvariantCulture).Replace(".",string.Empty);
EDIT2: Also there is another general idea that do not use Replace
function (but also it does not use the String.Format
) 编辑2:还有另一个一般的想法 ,不使用Replace
功能(但它也不使用String.Format
)
var stringValue = string.Join("", value.ToString().Where(char.IsDigit));
Also another similar idea: 另外一个类似的想法:
var stringValue = new string(value.ToString().Where(char.IsDigit).ToArray());
First of all, please read my comment to the question. 首先,请阅读我对该问题的评论。 As i mentioned there, string format for numeric values depends on regional settings. 正如我在那里提到的,数值的字符串格式取决于区域设置。 So, below line 所以,在线以下
mbar.HealthLabel.text = String.Format("{0:0.0}", _hp);
will return: 2,25 (as to the polish numeric standard) 将返回: 2,25 (关于波兰数字标准)
In my opinion you need something like this: 在我看来,你需要这样的东西:
mbar.HealthLabel.text = String.Format("{0:D}", Math.Floor(_hp*100));
For furhter details, please see: 有关详细信息,请参阅:
Up to Microsoft.NET Framework 4.7 there is no way to solve this when we are only allowed to modify the format string ("template"). 当我们只允许修改格式字符串(“template”)时,无法解决这个问题。 All solutions require to either: 所有解决方案都要求:
If you want to eliminate the decimal separtor ("escape the dot", as you've put it), try replacing the decimal separator with empty string : 如果你想消除十进制separtor(“逃避点”,就像你说的那样),尝试用 空字符串 替换小数分隔符 :
string result = String
.Format("{0:0.0}", _hp)
.Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, "");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.