Johann
Johann

Reputation: 67

Convert a string to float

I have a string in this format: "123.46.789-01". I must cast it to float, and I was doing it this way: float.parse(stringVariable.Replace(".", "").Replace("-", "")) where stringVariable is the string with the value described above.

This cast is generating a wrong cast value, wich is 1.141085E+10.

I've tried converting in many other ways, like Convert.ToSingle, but no success on that. You guys can help me with that? I'm wondering if this kind of number fits on float data type at all...

Thanks in advance!

Upvotes: 4

Views: 25581

Answers (3)

cederlof
cederlof

Reputation: 7383

There are a lot of problems using floats. I tend to use doubles, which does the same thing(?)

When I run:

var inputString = "123.46.789-01";
var strippedString = inputString.Replace(".", "").Replace("-", "");
float floatValue = float.Parse(strippedString);

I get the value: 1,234679E+09 which is an alternative way of displaying 1234678901.

Confirm by adding this line to the code:

double doubleValue = Convert.ToDouble(floatValue);

and you'll get 1234678901.

Upvotes: 3

Sid
Sid

Reputation: 317

Try this! i am getting output 1234678901

string cpf = "123.46.789-01";
decimal result= decimal.Parse(Regex.Replace(cpf, "[^0-9]", ""), System.Globalization.NumberStyles.Any);

Upvotes: 1

Konrad Kokosa
Konrad Kokosa

Reputation: 16878

This works for me and is more general (as I am removing all non-digits):

float result = float.Parse(Regex.Replace(str, "[^0-9]", ""));

Upvotes: 1

Related Questions