Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert double/float to string

I need to convert a floating point number to an equivalent string in decimal (or other base). Conversion at first needs to be done in the format xE+0 where x is the floating point number.

The idea I have is to first truncate the floating point number into a temporary integer and then convert that integer into string, and then consider the fractional part, multiply it with 10 while the fractional part does not become 0. After the fractional part is transferred into the left side of the decimal point, apply the integer to string function again and convert the fraction part to string. Is there a better way, which will be faster than this? Will this method induce any kind of side effects?

To convert the floating point number into exponential representation shall I do the same as above and then adjust the power? Or directly bitmask the IEEE 754 floating point representation and convert each part into string.

Note: No other functions could be used, because I have access to absolutely no library functions. This code goes into a toy kernel.

like image 931
phoxis Avatar asked Aug 29 '11 09:08

phoxis


People also ask

Can you convert a float to a string?

We can convert float to a string easily using str() function.

Can double be converted to float?

Using TypeCasting to Convert Double to Float in Java To define a float type, we must use the suffix f or F , whereas it is optional to use the suffix d or D for double. The default value of float is 0.0f , while the default value of double is 0.0d .


2 Answers

Use snprintf() from stdlib.h. Worked for me.

double num = 123412341234.123456789;  char output[50];  snprintf(output, 50, "%f", num);  printf("%s", output); 
like image 114
sujeeth.mr Avatar answered Oct 03 '22 21:10

sujeeth.mr


The only exact solution is to perform arbitrary-precision decimal arithmetic for the base conversion, since the exact value can be very long - for 80-bit long double, up to about 10000 decimal places. Fortunately it's "only" up to about 700 places or so for IEEE double.

Rather than working with individual decimal digits, it's helpful to instead work base-1-billion (the highest power of 10 that fits in a 32-bit integer) and then convert these "base-1-billion digits" to 9 decimal digits each at the end of your computation.

I have a very dense (rather hard to read) but efficient implementation here, under LGPL MIT license:

http://git.musl-libc.org/cgit/musl/blob/src/stdio/vfprintf.c?h=v1.1.6

If you strip out all the hex float support, infinity/nan support, %g/%f/%e variation support, rounding (which will never be needed if you only want exact answers), and other things you might not need, the remaining code is rather simple.

like image 25
R.. GitHub STOP HELPING ICE Avatar answered Oct 03 '22 21:10

R.. GitHub STOP HELPING ICE