Convert float to semicolon and dot

I have a nullable float. Internal decimal places can be separated by a period or a comma, for example. 1,2 or 1,2. I need this float as a string to compare it with Regex. If I use the Convert.toString method, the semicolon is 12, not 1.2. How to convert float to String without losing a comma or dot? I alredy tried to convert it with different cultures.

thanks for the help

+4
source share
6 answers

The solution for this may be as follows:

float? num = 1.2f; string floatAsString = string.Format("{0:f}", num.Value); 

Perhaps you need to check if the HasValue property HasValue true before using the value. Additional examples: http://alexonasp.net/samples/stringformatting/

+3
source

String.Format () function with mask. But can you convert your strings to numbers, not your numbers, for comparison purposes? Should it be a regular expression comparison?

0
source

Are you sure the text field allows as "." and "," as a decimal separator (as opposed to a wildcard, also known as a thousands separator)?

If you are sure that you receive only decimal separators and do not group characters, replace "." on the "." . before using TryParse with InvariantCulture to convert a string to a float.
OR use the same culture in the code as on the client side, so both will use the same decimal separators.

As mentioned above, float has no concept of various decimal separators.

0
source

If it is a WinForm application, there is a static variable Application.CurrentCulture.NumberFormat.NumberDecimalSeparator .

Depending on the value, you get different results when converting ToString() . Try using this option to achieve the desired result.

0
source

Ok, I solved the problem. I made a converter in my xaml that allows you to enter values ​​with commas as a separator, so I do not need any checks if there are only two internal decimal places. Thank you for your help.

0
source

Try:

 string s = yourFloat.ToString(); 

Using an invariant culture is recommended if you want to be sure that your result will be in the correct form, but I would be surprised if there was a culture that does not display a comma or period.

I also suggest not using regular expressions to check the float value.

-1
source

All Articles