Double 10 decimal Point Precision - c++

We want to ensure that upto 10 decimal point values are kept while converting a double value to a string.
When we tried %e or %f, it will not keep more than 5 decimal points.
When we tried %.14f, the small values (less than 1.0e-20) are not properly converted to string.
What format string to be used to keep upto 10 decimal points for double values?

Try %.17g to print with the most appropriate format for the double in question.
printf("%.17g\n", 10000.);
printf("%.17g\n", 240.0008);
printf("%.17g\n", 0.0000000013);
10000
240.0008
1.3000000000000001e-009

I hope you do know that the float type (single-precision floating point) only ever keeps six decimal digits of precision? No conversion specifier can give precision that isn't there to begin with... (The double type keeps about 15 digits of precision, FYI.)
Link: http://en.wikipedia.org/wiki/Floating_point#Internal_representation
Update: JasonD has the answer to your updated question. Keeping this up for posteriority.

Float can store this number of decimal only if the number is small, otherwise use double.
In this example %.17g and %.14f are working without problem :
#include <stdio.h>
int main(void)
{
double v = 0.12345678912345;
printf("%.17g %.14f \n", v, v);
return 0;
}
Displayed result :
0.12345678912345 0.12345678912345
From the documentation
f : Decimal floating point, lowercase 392.65
e : Scientific notation (mantissa/exponent), lowercase 3.9265e+2
g : Use the shortest representation: %e or %f 392.65
So using %.14f it is fine
Edit:
the small values (less than 1.0e-20) are not properly converted to string.
To display more than 20 decimal, you should use long double... But if you only need to store 1.0e-20 and do not need to print more than 6 decimal, float can hold it.
For long double, you need to use something like %.21Lg. For example :
#include <stdio.h>
int main(void)
{
long double v = 0.123456789123456789123456789;
printf("%.21Lg %.21Lf \n", v, v);
return 0;
}

Related

How to round a floating point type to two decimals or more in C++? [duplicate]

How can I round a float value (such as 37.777779) to two decimal places (37.78) in C?
If you just want to round the number for output purposes, then the "%.2f" format string is indeed the correct answer. However, if you actually want to round the floating point value for further computation, something like the following works:
#include <math.h>
float val = 37.777779;
float rounded_down = floorf(val * 100) / 100; /* Result: 37.77 */
float nearest = roundf(val * 100) / 100; /* Result: 37.78 */
float rounded_up = ceilf(val * 100) / 100; /* Result: 37.78 */
Notice that there are three different rounding rules you might want to choose: round down (ie, truncate after two decimal places), rounded to nearest, and round up. Usually, you want round to nearest.
As several others have pointed out, due to the quirks of floating point representation, these rounded values may not be exactly the "obvious" decimal values, but they will be very very close.
For much (much!) more information on rounding, and especially on tie-breaking rules for rounding to nearest, see the Wikipedia article on Rounding.
Using %.2f in printf. It only print 2 decimal points.
Example:
printf("%.2f", 37.777779);
Output:
37.77
Assuming you're talking about round the value for printing, then Andrew Coleson and AraK's answer are correct:
printf("%.2f", 37.777779);
But note that if you're aiming to round the number to exactly 37.78 for internal use (eg to compare against another value), then this isn't a good idea, due to the way floating point numbers work: you usually don't want to do equality comparisons for floating point, instead use a target value +/- a sigma value. Or encode the number as a string with a known precision, and compare that.
See the link in Greg Hewgill's answer to a related question, which also covers why you shouldn't use floating point for financial calculations.
How about this:
float value = 37.777779;
float rounded = ((int)(value * 100 + .5) / 100.0);
printf("%.2f", 37.777779);
If you want to write to C-string:
char number[24]; // dummy size, you should take care of the size!
sprintf(number, "%.2f", 37.777779);
Always use the printf family of functions for this. Even if you want to get the value as a float, you're best off using snprintf to get the rounded value as a string and then parsing it back with atof:
#include <math.h>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
double dround(double val, int dp) {
int charsNeeded = 1 + snprintf(NULL, 0, "%.*f", dp, val);
char *buffer = malloc(charsNeeded);
snprintf(buffer, charsNeeded, "%.*f", dp, val);
double result = atof(buffer);
free(buffer);
return result;
}
I say this because the approach shown by the currently top-voted answer and several others here -
multiplying by 100, rounding to the nearest integer, and then dividing by 100 again - is flawed in two ways:
For some values, it will round in the wrong direction because the multiplication by 100 changes the decimal digit determining the rounding direction from a 4 to a 5 or vice versa, due to the imprecision of floating point numbers
For some values, multiplying and then dividing by 100 doesn't round-trip, meaning that even if no rounding takes place the end result will be wrong
To illustrate the first kind of error - the rounding direction sometimes being wrong - try running this program:
int main(void) {
// This number is EXACTLY representable as a double
double x = 0.01499999999999999944488848768742172978818416595458984375;
printf("x: %.50f\n", x);
double res1 = dround(x, 2);
double res2 = round(100 * x) / 100;
printf("Rounded with snprintf: %.50f\n", res1);
printf("Rounded with round, then divided: %.50f\n", res2);
}
You'll see this output:
x: 0.01499999999999999944488848768742172978818416595459
Rounded with snprintf: 0.01000000000000000020816681711721685132943093776703
Rounded with round, then divided: 0.02000000000000000041633363423443370265886187553406
Note that the value we started with was less than 0.015, and so the mathematically correct answer when rounding it to 2 decimal places is 0.01. Of course, 0.01 is not exactly representable as a double, but we expect our result to be the double nearest to 0.01. Using snprintf gives us that result, but using round(100 * x) / 100 gives us 0.02, which is wrong. Why? Because 100 * x gives us exactly 1.5 as the result. Multiplying by 100 thus changes the correct direction to round in.
To illustrate the second kind of error - the result sometimes being wrong due to * 100 and / 100 not truly being inverses of each other - we can do a similar exercise with a very big number:
int main(void) {
double x = 8631192423766613.0;
printf("x: %.1f\n", x);
double res1 = dround(x, 2);
double res2 = round(100 * x) / 100;
printf("Rounded with snprintf: %.1f\n", res1);
printf("Rounded with round, then divided: %.1f\n", res2);
}
Our number now doesn't even have a fractional part; it's an integer value, just stored with type double. So the result after rounding it should be the same number we started with, right?
If you run the program above, you'll see:
x: 8631192423766613.0
Rounded with snprintf: 8631192423766613.0
Rounded with round, then divided: 8631192423766612.0
Oops. Our snprintf method returns the right result again, but the multiply-then-round-then-divide approach fails. That's because the mathematically correct value of 8631192423766613.0 * 100, 863119242376661300.0, is not exactly representable as a double; the closest value is 863119242376661248.0. When you divide that back by 100, you get 8631192423766612.0 - a different number to the one you started with.
Hopefully that's a sufficient demonstration that using roundf for rounding to a number of decimal places is broken, and that you should use snprintf instead. If that feels like a horrible hack to you, perhaps you'll be reassured by the knowledge that it's basically what CPython does.
Also, if you're using C++, you can just create a function like this:
string prd(const double x, const int decDigits) {
stringstream ss;
ss << fixed;
ss.precision(decDigits); // set # places after decimal
ss << x;
return ss.str();
}
You can then output any double myDouble with n places after the decimal point with code such as this:
std::cout << prd(myDouble,n);
There isn't a way to round a float to another float because the rounded float may not be representable (a limitation of floating-point numbers). For instance, say you round 37.777779 to 37.78, but the nearest representable number is 37.781.
However, you can "round" a float by using a format string function.
You can still use:
float ceilf(float x); // don't forget #include <math.h> and link with -lm.
example:
float valueToRound = 37.777779;
float roundedValue = ceilf(valueToRound * 100) / 100;
In C++ (or in C with C-style casts), you could create the function:
/* Function to control # of decimal places to be output for x */
double showDecimals(const double& x, const int& numDecimals) {
int y=x;
double z=x-y;
double m=pow(10,numDecimals);
double q=z*m;
double r=round(q);
return static_cast<double>(y)+(1.0/m)*r;
}
Then std::cout << showDecimals(37.777779,2); would produce: 37.78.
Obviously you don't really need to create all 5 variables in that function, but I leave them there so you can see the logic. There are probably simpler solutions, but this works well for me--especially since it allows me to adjust the number of digits after the decimal place as I need.
Use float roundf(float x).
"The round functions round their argument to the nearest integer value in floating-point format, rounding halfway cases away from zero, regardless of the current rounding direction." C11dr ยง7.12.9.5
#include <math.h>
float y = roundf(x * 100.0f) / 100.0f;
Depending on your float implementation, numbers that may appear to be half-way are not. as floating-point is typically base-2 oriented. Further, precisely rounding to the nearest 0.01 on all "half-way" cases is most challenging.
void r100(const char *s) {
float x, y;
sscanf(s, "%f", &x);
y = round(x*100.0)/100.0;
printf("%6s %.12e %.12e\n", s, x, y);
}
int main(void) {
r100("1.115");
r100("1.125");
r100("1.135");
return 0;
}
1.115 1.115000009537e+00 1.120000004768e+00
1.125 1.125000000000e+00 1.129999995232e+00
1.135 1.134999990463e+00 1.139999985695e+00
Although "1.115" is "half-way" between 1.11 and 1.12, when converted to float, the value is 1.115000009537... and is no longer "half-way", but closer to 1.12 and rounds to the closest float of 1.120000004768...
"1.125" is "half-way" between 1.12 and 1.13, when converted to float, the value is exactly 1.125 and is "half-way". It rounds toward 1.13 due to ties to even rule and rounds to the closest float of 1.129999995232...
Although "1.135" is "half-way" between 1.13 and 1.14, when converted to float, the value is 1.134999990463... and is no longer "half-way", but closer to 1.13 and rounds to the closest float of 1.129999995232...
If code used
y = roundf(x*100.0f)/100.0f;
Although "1.135" is "half-way" between 1.13 and 1.14, when converted to float, the value is 1.134999990463... and is no longer "half-way", but closer to 1.13 but incorrectly rounds to float of 1.139999985695... due to the more limited precision of float vs. double. This incorrect value may be viewed as correct, depending on coding goals.
Code definition :
#define roundz(x,d) ((floor(((x)*pow(10,d))+.5))/pow(10,d))
Results :
a = 8.000000
sqrt(a) = r = 2.828427
roundz(r,2) = 2.830000
roundz(r,3) = 2.828000
roundz(r,5) = 2.828430
double f_round(double dval, int n)
{
char l_fmtp[32], l_buf[64];
char *p_str;
sprintf (l_fmtp, "%%.%df", n);
if (dval>=0)
sprintf (l_buf, l_fmtp, dval);
else
sprintf (l_buf, l_fmtp, dval);
return ((double)strtod(l_buf, &p_str));
}
Here n is the number of decimals
example:
double d = 100.23456;
printf("%f", f_round(d, 4));// result: 100.2346
printf("%f", f_round(d, 2));// result: 100.23
I made this macro for rounding float numbers.
Add it in your header / being of file
#define ROUNDF(f, c) (((float)((int)((f) * (c))) / (c)))
Here is an example:
float x = ROUNDF(3.141592, 100)
x equals 3.14 :)
Let me first attempt to justify my reason for adding yet another answer to this question. In an ideal world, rounding is not really a big deal. However, in real systems, you may need to contend with several issues that can result in rounding that may not be what you expect. For example, you may be performing financial calculations where final results are rounded and displayed to users as 2 decimal places; these same values are stored with fixed precision in a database that may include more than 2 decimal places (for various reasons; there is no optimal number of places to keep...depends on specific situations each system must support, e.g. tiny items whose prices are fractions of a penny per unit); and, floating point computations performed on values where the results are plus/minus epsilon. I have been confronting these issues and evolving my own strategy over the years. I won't claim that I have faced every scenario or have the best answer, but below is an example of my approach so far that overcomes these issues:
Suppose 6 decimal places is regarded as sufficient precision for calculations on floats/doubles (an arbitrary decision for the specific application), using the following rounding function/method:
double Round(double x, int p)
{
if (x != 0.0) {
return ((floor((fabs(x)*pow(double(10.0),p))+0.5))/pow(double(10.0),p))*(x/fabs(x));
} else {
return 0.0;
}
}
Rounding to 2 decimal places for presentation of a result can be performed as:
double val;
// ...perform calculations on val
String(Round(Round(Round(val,8),6),2));
For val = 6.825, result is 6.83 as expected.
For val = 6.824999, result is 6.82. Here the assumption is that the calculation resulted in exactly 6.824999 and the 7th decimal place is zero.
For val = 6.8249999, result is 6.83. The 7th decimal place being 9 in this case causes the Round(val,6) function to give the expected result. For this case, there could be any number of trailing 9s.
For val = 6.824999499999, result is 6.83. Rounding to the 8th decimal place as a first step, i.e. Round(val,8), takes care of the one nasty case whereby a calculated floating point result calculates to 6.8249995, but is internally represented as 6.824999499999....
Finally, the example from the question...val = 37.777779 results in 37.78.
This approach could be further generalized as:
double val;
// ...perform calculations on val
String(Round(Round(Round(val,N+2),N),2));
where N is precision to be maintained for all intermediate calculations on floats/doubles. This works on negative values as well. I do not know if this approach is mathematically correct for all possibilities.
...or you can do it the old-fashioned way without any libraries:
float a = 37.777779;
int b = a; // b = 37
float c = a - b; // c = 0.777779
c *= 100; // c = 77.777863
int d = c; // d = 77;
a = b + d / (float)100; // a = 37.770000;
That of course if you want to remove the extra information from the number.
this function takes the number and precision and returns the rounded off number
float roundoff(float num,int precision)
{
int temp=(int )(num*pow(10,precision));
int num1=num*pow(10,precision+1);
temp*=10;
temp+=5;
if(num1>=temp)
num1+=10;
num1/=10;
num1*=10;
num=num1/pow(10,precision+1);
return num;
}
it converts the floating point number into int by left shifting the point and checking for the greater than five condition.

Convert string into float in C++ with full Significant figures [Fixed working in Dev C++]

I want to convert the String which contains numerical Float into Float or Double Data type values with full significant figures Please help me to fix this
#include <sstream>
#include<iostream>
#include<string>
using namespace std;
int main()
{
string q = "23.3453535";
float f;
istringstream(q) >>f;
f=1.0*f; // stack-overflow viewer it is an example because i want to process this float value
cout<<f;
}
/*OutPut is:
23.3454
but i want this
23.3453535
*/
If you want to control the precision then include #include <iomanip> and use std::cout << std::setprecision(17); to set the number of digits you want. Also float has 6 significant bits precision whereas double has 12. So whenever your string has more than 6 digits in decimal there is a possibility of loosing the precision.
There are TWO issues here:
You are running into the default formatting of floating point output on std::ostream, which is 6 digits. Use std::setprecision(n) to increase the precision to cover enough decimal places as you wish.
You are trying to get more precision out of a float than it will support. "23.3453535" is 9 digits long, so with 3.3 digits per digit it is approximately 30 bits are needed to store this number with all bits preserved. (exactly, you need ceil(log(233453535)/log(2)) which is 28). A float only has 23 bits to store the mantissa, so whilst the value is in the representable range, some of the last digits will disappear. You can fix this by using double instead of float - but as float, you will not ever get 9 valid decimal digits.

why double and long double are giving different answer in the following program

This code is calculating the Nth term of a series which is defined as
Tn+2=(Tn+1)^2+Tn, where 1st and 2nd terms are given as a and b in the code.
#include<iostream>
#include<string>
using namespace std;
int main()
{
int a,b,n;
char ch[100];
cin>>a>>b>>n;
long double res[3];
res[0]=a,res[1]=b;
for(int i=n-2;i>0;i--)
{
res[2]=res[1]*res[1]+res[0];
res[0]=res[1];
res[1]=res[2];
}
sprintf(ch,"%.0Lf",res[2]);
cout<<ch;
return 0;
}
Input: 0 1 10
Output:
84266613096281242861568 // in case of double res[3];
84266613096281243385856 // in case of long double res[3];
correct output : 84266613096281243382112
Since it is going out of the range of integer, therefore I am using double/long double.
But the problem is I am getting different output for double and long double, while none of the intermediate values are having non zero digit after decimal point, so there should not be any rounding off, I guess.
while none of the intermediate values are having non zero digit after decimal point, so there should not be any rounding off, I guess.
This assumption is just plain wrong. All floating point numbers like double etc. are stored like
mantissa * 2^exponent
with a finite number of bits for both the mantissa and the exponent. So floating point numbers can store a fixed number of significant digits (for a double converted to decimal representation, around 16 usually). If a number has more digits before the decimal point, rounding will happen and the total rounding error gets bigger the more digits you need to "forget".
If you want more details on this, the most common floating point implementations follow the IEEE floating point standard.

How to convert a string to a double with 6-digit precision in C++?

I want to know how to convert a string like "1234.123456" to double or float.
I need at least 3 digits precision (i.e. 3 digits after the decimal point, regardless of the number of digits before the point).
The exact value 1234.123456 isn't representable in any of the usual
machine floating point formats. All you can do is choose how much
accuracy you need, and use it. (On most modern machines, double has
16 digits precision. But that still doesn't mean that all 16 digit
values are exactly representable.)
As for the conversion, just do what you would do to convert any type:
std::istringstream s( "1234.123456" );
double d;
s >> d;
And read
http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html. It will
explain the basic minimum you need to know in order to safely use
machine floating point.
#include<stdlib.h>
int main()
{
double dnum = atof( "1234.123456" ) ;
printf ( "%f\n" , dnum ) ;
return 0 ;
}

union consisting of float : completely insane output

#include <stdio.h>
union NumericType
{
float value;
int intvalue;
}Values;
int main()
{
Values.value = 1094795585.00;
printf("%f \n",Values.value);
return 0;
}
This program outputs as :
1094795648.000000
Can anybody explain Why is this happening? Why did the value of the float Values.value increase? Or am I missing something here?
First off, this has nothing whatsoever to do with the use of a union.
Now, suppose you write:
int x = 1.5;
printf("%d\n", x);
what will happen? 1.5 is not an integer value, so it gets converted to an integer (by truncation) and x so actually gets the value 1, which is exactly what is printed.
The exact same thing is happening in your example.
float x = 1094795585.0;
printf("%f\n", x);
1094795585.0 is not representable as a single precision floating-point number, so it gets converted to a representable value. This happens via rounding. The two closest values are:
1094795520 (0x41414100) -- closest `float` smaller than your number
1094795585 (0x41414141) -- your number
1094795648 (0x41414180) -- closest `float` larger than your number
Because your number is slightly closer to the larger value (this is somewhat easier to see if you look at the hexadecimal representation), it rounds to that value, so that is the value stored in x, and that is the value that is printed.
A float isn't as precise as you would like it to be. Its mantissa of an effective 24 bit only provides a precision of 7-8 decimal digits. Your example requires 10 decimal digits precision. A double has an effective 53 bit mantissa which provides 15-16 digits of precision which is enough for your purpose.
It's because your float type doesn't have the precision to display that number. Use a double.
floats only have 7 digits of precision
See this link for more details:
link text
When I do this, I get the same results:
int _tmain(int argc, _TCHAR* argv[])
{
float f = 1094795585.00f;
// 1094795648.000000
printf("%f \n",f);
return 0;
}
I simply don't understand why people use floats - they are often no faster than doubles and may be slower. This code:
#include <stdio.h>
union NumericType
{
double value;
int intvalue;
}Values;
int main()
{
Values.value = 1094795585.00;
printf("%lf \n",Values.value);
return 0;
}
produces:
1094795585.000000
By default a printf of float with %f will give precision 6 after the decimal. If you want a precision of 2 digits after the decimal use %.2f.
Even the below gives same result
#include <stdio.h>
union NumericType
{
float value;
int intvalue;
}Values;
int main()
{
Values.value = 1094795585;
printf("%f \n",Values.value);
return 0;
}
Result
./a.out
1094795648.000000
It only complicates things to speak of decimal digits because this is binary arithmetic. To explain this we can begin by looking at the set of integers in the single precision format where all the integers are representable. Since the single precision format has 23+1=24 bits of precision that means that the range is
0 to 2^24-1
This is not good or detailed enough for explaining so I'll refine it further to
0 to 2^24-2^0 in steps of 2^0
The next higher set is
0 to 2^25-2^1 in steps of 2^1
The next lower set is
0 to 2^23-2^-1 in steps of 2^-1
Your number, 1094795585 (0x41414141 in hex), falls in the range that has a maximum of slightly less than 2^31 =. That range can be expressed in detail as 0 to 2^31-2^7 in steps of 2^7. It's logical because 2^31 is 7 powers of 2 greater than 24. Therefore the increments must also be 7 powers of 2 greater.
Looking at the "next lower" and "next higher" values mentioned in another post we see that the difference between them is 128 i e 2^7.
There's really nothing strange or weird or funny or even magic about this. It's actually absolutely clear and quite simple.