I want to store a float value into string without lossing or adding any single precision digits.
For example if my float value is 23.345466467 , I want my string to have str = "23.345466467" exact digits.
I tried using CString format function with %f. Its giving only first 6 precision. or if i use %10 , if my float value is having less than 10 precision,its adding some more junk precision. I want to get exact float value into my string. how to do this?
The Float. toString() method can also be used to convert the float value to a String. The toString() is the static method of the Float class.
We can also convert a float to a string using the str() function.
Description. The atof() function converts a character string to a double-precision floating-point value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type.
Method 1: Conversion using int(): To convert a float value to int we make use of the built-in int() function, this function trims the values after the decimal point and returns only the integer/whole number part. Example 1: Number of type float is converted to a result of type int.
See the nice detailed discussion in http://randomascii.wordpress.com/2012/03/08/float-precisionfrom-zero-to-100-digits-2/ .
The short answer is that the minimum precision is the following:
printf("%1.8e", d); // Round-trippable float, always with an exponent
printf("%.9g", d); // Round-trippable float, shortest possible
printf("%1.16e", d); // Round-trippable double, always with an exponent
printf("%.17g", d); // Round-trippable double, shortest possible
Or equivalently, with a std::ostream& os
:
os << scientific << setprecision(8) << d; // float; always with an exponent
os << defaultfloat << setprecision(9) << d; // float; shortest possible
os << scientific << setprecision(16) << d; // double; always with an exponent
os << defaultfloat << setprecision(17) << d; // double; shortest possible
That would depend upon whether your float value 23.345466467 is exactly representable (likely not)
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Why Floating-Point Numbers May Lose Precision
I would also question why you need to do this? What are you going to use the string representation for? Are you aware of the double and decimal types?
[Untested: you could try casting to double and then using "%d" Maybe this will pull in the extra 'guard' digits' but it still won't work for all values]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With