nunos
nunos

Reputation: 21389

How to return a float point number with a defined number of decimal places?

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.

Upvotes: 0

Views: 4173

Answers (4)

sth
sth

Reputation: 229593

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.

Upvotes: 4

Jordan Messina
Jordan Messina

Reputation: 1531

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.

Upvotes: 6

Larry Watanabe
Larry Watanabe

Reputation: 10184

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.

Upvotes: 2

Pascal Cuoq
Pascal Cuoq

Reputation: 80276

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.

Upvotes: 4

Related Questions