在Python中四舍五入小数数字。

huangapple go评论58阅读模式
英文:

round decimal numbers in Python

问题

如何在Python中渲染小数?例如,在数字3.14373873中,只包括4及其之前的数字。

我想要从特定位置开始四舍五入小数:

例如:

3.14373873 -> 3.14
英文:

How can I render decimal numbers in Python? For example, in the number 3.14373873 only up to and including the number 4.

I want to round the decimal numbers from a specific place:

As example:

3.14373873 -> 3.14

答案1

得分: 2

你可以使用round()函数:

示例:

p = round(50.12345,3)
print(p)

输出:

50.123

示例2:

# 对于整数
print(round(15))

# 对于浮点数
print(round(51.6))
print(round(51.5))
print(round(51.4))

输出:

15
52
52
51
英文:

you can use the round() function:

https://www.w3schools.com/python/ref_func_round.asp

Example:

p = round(50.12345,3)
print(p)

Output:

 50.123

Example 2:

# for integers
print(round(15))

# for floating point
print(round(51.6))
print(round(51.5))
print(round(51.4))

Output:

15  
52  
52  
51  

答案2

得分: 1

你可以这样做:

print(round(3.14373873, 4))
英文:

You can do this:

print(round(3.14373873, 4))   

答案3

得分: 1

你可以使用round()函数:

示例:

x = round(1.54321, 2)

print(x)

  • 你可以在程序中指定要保留多少位数的数值。

  • 由于指定了2位数,所以输出将为1.54。

  • 如果你指定了3位数,那么输出将是1.543,以此类推。

英文:

you can use the round() function:-

Example :

x = round(1.54321, 2)

print(x)

  • You can mention the value after the how many digits you have to store on your program

  • Your output will be 1.54 because of the mention of 2 digits...

  • If you have mentioned 3 digits then the output will be 1.543 like that

答案4

得分: 0

标准Python库中的round函数可用于将浮点数舍入到小数点后所需的位数 -:

round(decimal_num, num_of_digits_to_round_to)

要将3.14373873舍入为3.14,可以执行以下操作 -:

round(3.14373873, 2)

请参考官方Python Wiki以获取更多信息 -:

> round(number, ndigits=None)

> 将数字四舍五入到小数点后的ndigits精度。如果省略了ndigits或为None,则它将返回最接近其输入的整数。

英文:

The round function from the standard python library can be used to round floats to the desired number of digits after decimal point -:

round(decimal_num, num_of_digits_to_round_to)

To round 3.14373873 to just 3.14, you can do the following -:

round(3.14373873, 2)

Refer to official python wiki for more info -:

> round(number, ndigits=None)
>
> Return number rounded to ndigits precision
> after the decimal point. If ndigits is omitted or is None, it returns
> the nearest integer to its input.

huangapple
  • 本文由 发表于 2023年7月17日 20:37:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76704523.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定