Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to float?

#include<stdio.h> #include<string.h>  int main()  {     char s[100] ="4.0800" ;       printf("float value : %4.8f\n" ,(float) atoll(s));      return 0;  } 

I expect the output should be 4.08000000 whereas I got only 4.00000000.

Is there any way to get the numbers after the dot?

like image 453
abubacker Avatar asked Oct 31 '11 07:10

abubacker


People also ask

How do you convert a string to a float in Python?

In Python, we can use float() to convert String to float. and we can use int() to convert String to an integer.

Can we convert string to float in java?

For converting strings to floating-point values, we can use Float. parseFloat() if we need a float primitive or Float. valueOf() if we prefer a Float object.

How do you convert a string to a float in C ++?

The easiest way to convert a string to a floating-point number is by using these C++11 functions: std::stof() - convert string to float. std::stod() - convert string to double. std::stold() - convert string to long double .


2 Answers

Use atof() or strtof()* instead:

printf("float value : %4.8f\n" ,atof(s));  printf("float value : %4.8f\n" ,strtof(s, NULL));  

http://www.cplusplus.com/reference/clibrary/cstdlib/atof/
http://www.cplusplus.com/reference/cstdlib/strtof/

  • atoll() is meant for integers.
  • atof()/strtof() is for floats.

The reason why you only get 4.00 with atoll() is because it stops parsing when it finds the first non-digit.

*Note that strtof() requires C99 or C++11.

like image 121
Mysticial Avatar answered Oct 03 '22 15:10

Mysticial


Unfortunately, there is no way to do this easily. Every solution has its drawbacks.

  1. Use atof() or strtof() directly: this is what most people will tell you to do and it will work most of the time. However, if the program sets a locale or it uses a library that sets the locale (for instance, a graphics library that displays localised menus) and the user has their locale set to a language where the decimal separator is not . (such as fr_FR where the separator is ,) these functions will stop parsing at the . and you will stil get 4.0.

  2. Use atof() or strtof() but change the locale; it's a matter of calling setlocale(LC_ALL|~LC_NUMERIC, ""); before any call to atof() or the likes. The problem with setlocale is that it will be global to the process and you might interfer with the rest of the program. Note that you might query the current locale with setlocale() and restore it after you're done.

  3. Write your own float parsing routine. This might be quite quick if you do not need advanced features such as exponent parsing or hexadecimal floats.

Also, note that the value 4.08 cannot be represented exactly as a float; the actual value you will get is 4.0799999237060546875.

like image 22
sam hocevar Avatar answered Oct 03 '22 16:10

sam hocevar