15,743,429 members
See more:
Hi,
i want to know is it possible to approximate a decimal number to 2 places?
when i save a variable with a value 0.3 it saves it as 0.30000000001
anyway to prevent this or save the variable as 0.30 only?
thanks.
Posted
Richard MacCutchan 17-Sep-13 13:16pm
Floating point numbers are approximations of their real values. You need to understand the implications of this in computing; the main one being that you should not use floating point in financial applications.

## Solution 3

This is due to the nature of floating-point representations, e.g. `double` or `float`.
The values are stored as a binary value (of limited precision) and a binary scale factor.
The value `0.3` cannot be represented exactly in this way, so the closest possible value is stored, in this case `0.30000000001`.
You can control the way it is displayed with the formatting string of the `sprintf/printf/...`
This is also the reason that comparisons involving floating point values should usually include a little wiggle-room.
E.g., you shouldn't compare some value as exactly equal to 0.3 but that the difference between them is less than some acceptable tolerance.

nv3 17-Sep-13 14:20pm
Nice and detailed explanation. 5.
CPallini 17-Sep-13 16:00pm
5.

## Solution 4

H.Brydon 17-Sep-13 23:29pm
+5 - Exactly. The same page I searched for and was going to put in my own solution.
CPallini 18-Sep-13 1:41am
Thank you.

## Solution 2

The value of 0.3 can internally not be represented exactly as a floating point number. That is the reason you see 0.3000...0001. But when printing that value in an output you perform a rounding operation, for example:
C++
```double x = 0.3;
printf ("x = %.2f\n", x);
```

will print
C++
`x = 0.30`

just as expected. So printf does the rounding for you.

When dealing internally with floating point numbers I would suggest that you do not try to round them. Do all your calculation and do the rounding at the very end, when outputting the results.

ridoy 17-Sep-13 14:12pm
5ed!
nv3 17-Sep-13 14:18pm
Thanks!
CPallini 17-Sep-13 16:00pm
5.
nv3 17-Sep-13 16:56pm
Thank you!

v2

## Solution 5

Floating point Arithmetic may not be useful when doing a lot of operations with rational numbers. One possibility is to include a rational library.

When using C++, boost contains a good rational library:

boost/rational.hpp
[^]

With that library you can save a variable as 3.0 (and continue using that variable as a number, not a string).

## Solution 6

Thanks a lot guys, i really appreciate it.