Ashish Deb Ashish Deb - 10 months ago 51
C++ Question

How can I fix a double number with 2 digits after decimal point in cpp?

As like,

AC = sqrt((AB*AB)+(BC*BC));

BD = sqrt((BC*BC)+(CD*CD));

(where all variables are double type)

Here, i want the value of AC and BD fixed with 2 digits after decimal point and then I want to add AC and BD. Now, if i take (3 digits after decimal point) AC=4.564 and BD=4.789 the the result after adding them is 9.351. Again if i take (2digits after decimal point) AC=4.56 and BD=78 then the result after adding them is 9.34. Now if i print both result fixed with 2 digits after decimal point then it shows 9.35 and 9.34 respectively. But I want 9.34 as result.

Answer Source

If you're trying to print double values with 2 digits after the decimal then use modifiers to the conversion specifier like so:

printf ("%.2f", AC);

You should look at the round, ceil and floor functions and use them as follows:

ans = round (AC * 100.0) / 100.0

to do what you want. You'll find that you cannot represent all numbers as just two digits after the decimal so any comparisons you make should test for closeness of the answer to the target by +/- a small epsilon to the target value.

If you're trying to use the values computed for financial computation then this is very dangerous to do with the double type because certain values cannot be represented exactly with a limited number of bits of precision. You will suffer from accumulation of errors when performing financial computation with float/double types.