views:

161

answers:

4

So I know how to print a floating point number with a certain decimal places.

My question is how to return it with a specified number of decimal places?

Thanks.

+4  A: 

In order to get two decimal places, multiply the number by 100, floor it, then divide by 100.

And note that the number you will return will not really have only two decimal places because division by 100 cannot be represented exactly in IEEE-754 floating-point arithmetic most of the time. It will only be the closest representable approximation to a number with only two decimal places.

Pascal Cuoq
Why do you recommend that instead of `round(the_number, 2)` ?
John Machin
I don't :) I was giving a language-agnostic solution that used only basic operations available everywhere. I also hoped that someone would mention the `decimal` module, but no-one did... Ah, yes, sth. Well done that man!
Pascal Cuoq
+2  A: 

Floating point numbers have infinite number of decimal places. The physical representation on the computer is dependent on the representation of float, or double, or whatever and is dependent on a) language b) construct, e.g. float, double, etc. c) compiler implementation d) hardware.

Now, given that you have a representation of a floating point number (i.e. a real) within a particular language, is your question how to round it off or truncate it to a specific number of digits?

There is no need to do this within the return call, since you can always truncate/round afterwards. In fact, you would usually not want to truncate until actually printing, to preserve more precision. An exception might be if you wanted to ensure that results were consistent across different algorithms/hardware, ie. say you had some financial trading software that needed to pass unit tests across different languages/platforms etc.

Larry Watanabe
All floating point numbers can actually be written with a *finite* number of decimal digits (proof: multiply any finite sum of powers of 2 [including negative ones] by 10 to a large enough power, and you get an integer).
EOL
Sorry, I was confusing floating point with real numbers. By definition a floating point number is a finite string of digits.
Larry Watanabe
+7  A: 

You could use the round() function

The docs about it:

round(x[, n])

x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0.

Jordan Messina
+4  A: 

If you really want floating point numbers with a fixed precision you could use the decimal module. Those numbers have a user alterable precision and you could just do your calculation on two-digit decimals.

sth