简体   繁体   中英

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. Is it possible to escape a dot from the output string view with String.Format function ?

For. ex. 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.

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.

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 )

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)

In my opinion you need something like this:

mbar.HealthLabel.text = String.Format("{0:D}", Math.Floor(_hp*100));

For furhter details, please see:

Standard Numeric Format Strings

Custom Numeric Format Strings

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"). All solutions require to either:

  • Post-process the resulting string. Here, the closest for the special case with two decimals may be the % format
  • Compute the numeric argument first to make it integer
  • Write and apply a custom IFormatProvider implementation

If you want to eliminate the decimal separtor ("escape the dot", as you've put it), try replacing the decimal separator with empty string :

string result = String
 .Format("{0:0.0}", _hp)
 .Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, "");

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