C # line format: exit point

I have a line of code, something like:

mbar.HealthLabel.text = String.Format("{0:0.0}", _hp); 

Yield: 2.25, for example. Is it possible to avoid a point from representing the output string using the String.Format function?

For. ex. 225,

To make my question clearer, I need the same effect as:

 Math.Floor(_hp * 100).ToString(); 

But you need to do this using the String.Format template. Thanks.

+5
source share
4 answers

You can just do it this way.

 double value = 1.25; var stringValue = string.Format("{0:0}", value * 100, CultureInfo.InvariantCulture); //125 

EDIT: A more general solution would be to Replace point with an empty string, as indicated in the comments.

 double value = 1.25; var stringValue = value.ToString(CultureInfo.InvariantCulture).Replace(".",string.Empty); 

EDIT2: There is also another general idea that does not use the Replace function (but also does not use 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()); 
+4
source

First of all, read my comment on the question. As I mentioned, the string format for numeric values ​​depends on the regional settings. So below the line

 mbar.HealthLabel.text = String.Format("{0:0.0}", _hp); 

will return: 2.25 (as for the standard Polish standard)

In my opinion, you need something like this:

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

See below for more details:

Standard number format strings

Custom Number Format Strings

+2
source

Prior to Microsoft.NET Framework 4.7, there is no way to solve this problem if we are allowed to change only the format string ("template"). All solutions require either:

  • Postform the resulting string. Here, the closest to the special case with two decimal places may be the format%
  • First compute the numeric argument to make it integer.
  • Record and apply a special implementation of IFormatProvider.
+1
source

If you want to exclude the decimal separator ("run away from the point" as you expressed it), try replacing the decimal separator with an empty string:

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

All Articles