double truncate (double D,int n)
{
long multiplied;
double to_return;
multiplied = (D*pow(10,n)); // save only the first n digits after the decimal point . (as a long integer).
to_return = (multiplied / (pow(10,n)); // return to the trtunced (original ) number.
return (to_return);
}
for example:
in truncate (0.123456789,5) you'll get:
multiplied = 12345
to_return = 0.12345
That would work, but you have to understand that because of the limitations of the floating point format, not all decimal numbers will be expressible, thus when you truncate the number, you may see the last digit or two change in value. This is not problem with arnond's method, this is a limitation of the floating point system. For this reason, most programmer's don't truncate the value at all. They may limit the number of digits that print, but will try to retain full precision internally.
nietod is right, you can limit the number of digits you print using the format specifications of your favorite output function. for example: in printf() you should use "%.pf".
the 'p' stands for precision, i.e.: how many decimal places to display.
0
Your question, your audience. Choose who sees your identity—and your question—with question security.
Hi Arnod,
I am using C language because I can not use C++ due to some desing issue.
how do we proceed if the double has this value
UINT s = 10;
int n = 16;
double dx = (double)(s/100.0);
here is dx = 0.10000000000000001
The above logic does not work.
> you have to understand that because of the limitations of the floating point format, not all decimal numbers will be expressible, thus when you truncate the number, you may see the last digit or two change in value.
Thanks OZO. This is also my understanding.
One concern we are use C code in such a huge platform like Win32 (using VS 2008 compiler). Can this irreguarity be fix by the vendor in near future?
With this I stop with satisfaction.
0
Question has a verified solution.
Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.
double truncate (double D,int n)
{
long multiplied;
double to_return;
multiplied = (D*pow(10,n)); // save only the first n digits after the decimal point . (as a long integer).
to_return = (multiplied / (pow(10,n)); // return to the trtunced (original ) number.
return (to_return);
}
for example:
in truncate (0.123456789,5) you'll get:
multiplied = 12345
to_return = 0.12345