124

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...

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Mehmet
  • 1,704
  • 3
  • 16
  • 25
  • 2
    How do you know what it is converted to - that is how are you displaying the number – mmmmmm Jun 26 '12 at 08:25
  • 1
    Any idea why its ToSingle? And not ToFloat? – Lord Darth Vader Oct 20 '17 at 10:43
  • 1
    41.00027357629127 shall not be 4.10002732E+15 in scientific notation, unless of course your culture uses decimal comma instead of decimal point (and dot as thousands separator), so the number would actually read: 4100027357629127 consequently become displayed as 4.10002732E+15 – ljgww Oct 05 '18 at 07:45

7 Answers7

256

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.

Matthew Watson
  • 96,889
  • 9
  • 144
  • 240
27

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.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Tigran
  • 60,656
  • 8
  • 83
  • 120
26

You can use the following:

float asd = (float) Convert.ToDouble("41.00027357629127");
Cyber Progs
  • 3,240
  • 3
  • 27
  • 36
user4292249
  • 269
  • 3
  • 2
9

Use Convert.ToDouble("41.00027357629127");

Convert.ToDouble documentation

Uli Köhler
  • 12,474
  • 14
  • 64
  • 110
Ozgur Dogus
  • 913
  • 3
  • 14
  • 38
4

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#.

Community
  • 1
  • 1
jpe
  • 908
  • 5
  • 13
  • ı tired double.Parse it returns 4100027357629127.0 it is too bad – Mehmet Jun 26 '12 at 07:43
  • 2
    This sounds like the '.' character is not the decimal separator in your locale? Check out http://stackoverflow.com/questions/3870154/c-sharp-decimal-separator – jpe Jun 26 '12 at 07:48
0

You can double.Parse("41.00027357629127");

ABH
  • 3,351
  • 22
  • 25
-2

You can use parsing with double instead of float to get more precision value.

Learner
  • 1,496
  • 7
  • 25
  • 51