Convert string to float without Decimal Point and Exponential values

I have a scenario where I receive Phone Numbers and I have to save those numbers to database.

The Phone Number column in DB is of type float. But I am receiving phone numbers as string.

They may contain spaces or other characters.

I have written a code to remove characters and concert the resulting string to float. But I am getting output with exponential values, which in-turn getting modified in database.

I have a following code

string phone1="68 8845 62529";
System.Text.RegularExpressions.Regex digitsOnly = new System.Text.RegularExpressions.Regex(@"[^\d]");
float f = float.Parse(digitsOnly.Replace(phone1, string.Empty), System.Globalization.CultureInfo.InvariantCulture.NumberFormat);

My Input is "68 8845 62529"

I am getting the output as 6.888456E+9

Value getting stored in database 68884560512

I want the output as float f= 68884562529

Final datatype has to be float.

Please help.

Jon Skeet
people
quotationmark

The first problem is that choosing a floating point numeric type to represent a phone number is a terrible idea, which is likely to cause you problems all over the place. I would urge you to work out just how much effort it would take to change this bad decision. If you really, really can't change that though, you can at least improve on what you've got.

If you're using the SQL Server float type, without specifying a precision, that's probably equivalent to using double. So use double.Parse instead of float.Parse, and provide the value to the database as a double. Ignore any textual representation you may see along the way - you're just trying to preserve the numeric value of the double. The problem you're currently facing is that you're using the float type, which only has 7-9 digits of precision, but the value you're trying to parse has 11 digits.

You're effectively trying to store large integers. Using the float type gives you 53 bits of precision for those integers, so any integer less than 253 should be able to be stored precisely, and will hopefully not give you problems - but you'll need to make sure that when you inevitably want to turn it back into text, you do so without losing information. This should be okay for all numbers with only 14 digits or fewer.

As noted in comments, you're going to find it hard to understand numbers which differ based on whether they start with leading zeroes, which are clearly irrelevant in terms of a numeric value, but important in terms of a phone representation.

people

See more on this question at Stackoverflow