简体   繁体   English

如何将所有浮点数转换为两位小数,而不管浮点数有多少小数位,而无需重复转换代码?

[英]How to convert all floats to two decimal places regardless of number of decimal places float has without repeating convert code?

Goal目标

I want to convert all floats to two decimal places regardless of number of decimal places float has without repeating convert code .我想将所有浮点数转换为两位小数,而不管浮点数有多少小数位,而无需重复转换代码

For example, I want to convert例如,我想转换

50 to 50.00 5050.00

50.5 to 50.50 50.550.50

without repeating the convert code again and again.无需一次又一次地重复转换代码。 What I mean is explained in the following section - research.我的意思是在下一节中解释 - 研究。

Not what this question is about不是这个问题是关于什么的

This question is NOT about这个问题不是关于

  1. Only limiting floats to two decimal points - if there is less than two decimal points then I want it to have two decimal points with zeros for the unused spaces仅将浮点数限制为两个小数点 - 如果小数点少于两个,那么我希望它有两个小数点,未使用的空格为零

  2. Flooring the decimal or ceiling it对小数下限或上限

  3. Rounding the decimal off四舍五入

This question is also not a duplicate of this question .这个问题也不是这个问题的重复。

This question only answers the first part of my question - convert floats to two decimal places regardless of number of decimal places float has, not the second part - without repeating convert code这个问题只回答了我问题的第一部分 - 将浮点数转换为两位小数,无论浮点数有多少小数位,而不是第二部分 - 无需重复转换代码

Research研究

I found two ways I can achieve the convert.我找到了两种可以实现转换的方法。 One is using the decimal module.一种是使用decimal模块。

from decimal import *
TWOPLACES = Decimal(10) ** -2
print(Decimal('9.9').quantize(TWOPLACES))

Another, without using any other modules另一个,不使用任何其他模块

print(f"{9.9:.2f}")

However, that does not fully answer my question.但是,这并不能完全回答我的问题。 Realise that the code to convert keeps being needed to repeat itself?意识到要转换的代码需要不断重复吗? I keep having to repeat the code to convert again and again.我一直不得不重复代码来一次又一次地转换。 Sadly, my whole program is already almost completed and it will be quite a waste of time to add this code here and there so the format will be correct.可悲的是,我的整个程序已经快完成了,在这里和那里添加这段代码会很浪费时间,所以格式是正确的。 Is there any way to convert all floats to two decimal places regardless of number of decimal places float has without repeating convert code ?有没有办法将所有浮点数转换为两位小数,而不管浮点数有多少小数位,而无需重复转换代码

Use this function.使用这个 function。

def cvt_decimal(input):
    number = float(input)
    return ("%.2f" % number)

print(cvt_decimal(50))
print(cvt_decimal(50.5))

Output is: Output 是:

50.00
50.50


** Process exited - Return Code: 0 **
Press Enter to exit terminal

The bad news is: there is no "float" with "two decimal places".坏消息是:没有“小数点后两位”的“浮点数”。

Floating point numbers are represented internally with a fixed number of digits in base 2 .浮点数在内部用以2 为底的固定位数表示。 https://floating-point-gui.de/basic/ . https://floating-point-gui.de/basic/

And these are both efficient and accurate enough for almost all calculations we perform with any modern program.对于我们使用任何现代程序执行的几乎所有计算,这些都足够高效和准确。

What we normally want is that the human-readable text representation of a number, in all outputs of a program, shows only two digits.我们通常想要的是一个数字的人类可读文本表示,在程序的所有输出中,只显示两位数字。 And this is controlled at wherever your program is either writting the value to a text file, to the screen, or rendering it to an HTML template (which is "writing it to a text file", again).这可以在您的程序将值写入文本文件、屏幕或将其呈现到 HTML 模板(再次“将其写入文本文件”)的任何位置进行控制。

So, it happens that the same syntaxes that will convert a number to text, embedded in another string, allows additionally to control the exact output of the number.因此,将数字转换为文本的相同语法,嵌入另一个字符串,还允许控制数字的确切 output。 You put as an example print(f"{9.9:.2f}") .您以print(f"{9.9:.2f}")为例。 The only thing that looks impractical there is due to you hardcoding your number along with its conversion.唯一看起来不切实际的事情是由于您对号码及其转换进行了硬编码。 Typically, the number will be in a variable.通常,该数字将在一个变量中。

Them, all you have to do is writting, wherever you output the number:他们,你所要做的就是写,无论你在哪里 output 数字:

print(f"The value is: {myvar:.02f}")

instead of代替

print(f"The value is: {myvar}")

Or in whatever function you are calling that will need the rendered version of the number instead of print.或者在您调用的任何 function 中,都需要数字的呈现版本而不是打印。 Notice that the use of the word "rendered" here is deliberate: while your program is running, the number is stored in an efficient way in memory, directly usable by the CPU, that is not human readable.请注意,此处使用“渲染”一词是故意的:当您的程序运行时,该数字以有效的方式存储在 memory 中,CPU 可以直接使用,这不是人类可读的。 At any point you want to "see" the number, you have to convert it into text.在任何时候你想“看到”这个数字,你必须把它转换成文本。 It is just that some calls to it implicitly, like print(myvar) .只是一些隐式调用它,比如print(myvar) Then, just resort to explicitly converting it in these places - `print(f"{myvar:.02f}").然后,只需在这些地方显式转换它 - `print(f"{myvar:.02f}")。

really having 2 decimal places in memory memory 中确实有 2 个小数位

If you use decimal.Decimal , then yes, there are ways to keep the internal representation of the number with 2 decimal digits, but them, instead of just converting the number on output, you must convert it into a "2 decimal place" value on all inputs as well如果您使用decimal.Decimal ,那么是的,有一些方法可以用 2 个十进制数字保持数字的内部表示,但是它们,而不是仅仅转换 output 上的数字,您必须将其转换为“2 个小数位”值在所有输入

That means that whenever ingesting a number into your program, be it typed by the user, read from a binary file or database, or received via wire from a sensor, you have to apply a similar transform to the one used in the output as detailed above.这意味着,无论何时将数字输入到您的程序中,无论是用户键入的数字、从二进制文件或数据库中读取的数字,还是通过电线从传感器接收的数字,您都必须对 output 中使用的数字应用类似的转换,详细说明以上。 More precisely: you convert your float to a properly formatted string, and then convert that to a decimal.Decimal .更准确地说:您将浮点数转换为格式正确的字符串,然后将其转换为decimal.Decimal

And this will prevent your program of accumulating errors due to base conversion, but you will still need to force the format to 2 decimal places on every output, just like above.这将防止您的程序由于基本转换而累积错误,但您仍然需要在每个 output 上强制格式为 2 位小数,就像上面一样。

you can modify the decimal precision, even if you do any operation between 2 decimal types您可以修改小数精度,即使您在 2 个小数类型之间进行任何操作

import decimal
from decimal import Decimal

decimal.getcontext().prec = 2

a = Decimal('0.12345')
b = Decimal('0.12345')

print(a + b)

在此处输入图像描述

Decimal calculations are precise but it takes more time to do calculations, keep that in mind.十进制计算是精确的,但计算需要更多时间,请记住这一点。

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

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