简体   繁体   中英

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.

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.

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.

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.

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, eg float, double, etc. c) compiler implementation d) hardware.

Now, given that you have a representation of a floating point number (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM