Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting String To Float in C#

I am converting a string like "41.00027357629127", and I am using;

Convert.ToSingle("41.00027357629127");

or

float.Parse("41.00027357629127");

These methods return 4.10002732E+15.

When I convert to float I want "41.00027357629127". This string should be the same...

like image 840
Mehmet Avatar asked Jun 26 '12 07:06

Mehmet


People also ask

Can you cast a string to a float in C?

In the C Programming Language, the atof function converts a string to a floating-point number (double). The atof function skips all white-space characters at the beginning of the string, converts the subsequent characters as part of the number, and then stops when it encounters the first character that isn't a number.

How do you convert a string to a float?

We can convert a string to float in Python using float() function. It's a built-in function to convert an object to floating point number. Internally float() function calls specified object __float__() function.

What converts the string value into float?

We can convert String to float in java using Float. parseFloat() method.

What does atof stand for in C?

C Programming/stdlib. h/atof atof is a function in the C programming language that converts a string into a floating point numerical representation. atof stands for ASCII to float. It is included in the C standard library header file stdlib.


5 Answers

Your thread's locale is set to one in which the decimal mark is "," instead of ".".

Try using this:

float.Parse("41.00027357629127", CultureInfo.InvariantCulture.NumberFormat);

Note, however, that a float cannot hold that many digits of precision. You would have to use double or Decimal to do so.

like image 84
Matthew Watson Avatar answered Oct 05 '22 01:10

Matthew Watson


First, it is just a presentation of the float number you see in the debugger. The real value is approximately exact (as much as it's possible).

Note: Use always CultureInfo information when dealing with floating point numbers versus strings.

float.Parse("41.00027357629127",
      System.Globalization.CultureInfo.InvariantCulture);

This is just an example; choose an appropriate culture for your case.

like image 21
Tigran Avatar answered Oct 05 '22 02:10

Tigran


You can use the following:

float asd = (float) Convert.ToDouble("41.00027357629127");
like image 45
user4292249 Avatar answered Oct 05 '22 02:10

user4292249


Use Convert.ToDouble("41.00027357629127");

Convert.ToDouble documentation

like image 35
Ozgur Dogus Avatar answered Oct 05 '22 02:10

Ozgur Dogus


The precision of float is 7 digits. If you want to keep the whole lot, you need to use the double type that keeps 15-16 digits. Regarding formatting, look at a post about formatting doubles. And you need to worry about decimal separators in C#.

like image 37
jpe Avatar answered Oct 05 '22 02:10

jpe