简体   繁体   English

如何返回具有定义的小数位数的浮点数?

[英]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 您可以使用round()函数

The docs about it: 关于它的文档:

round(x[, n])

x rounded to n digits, rounding half to even. x四舍五入为n位数字,四舍五入为偶数。 If n is omitted, it defaults to 0. 如果省略n,则默认为0。

In order to get two decimal places, multiply the number by 100, floor it, then divide by 100. 为了获得小数点后两位,请将数字乘以100,将其取下,然后除以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. 并请注意,您返回的数字实际上不会只有两位小数,因为在大多数情况下,用IEEE-754浮点算术无法精确表示以100除。 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. 如果您确实想要固定精度的浮点数,则可以使用decimal模块。 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. 计算机上的物理表示形式取决于float或double或其他形式的表示,并且取决于a)语言b)构造,例如float,double等等。c)编译器实现d)硬件。

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. 说您有一些金融交易软件,需要通过不同语言/平台等进行单元测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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