怎么样将带有小数的数字四舍五入,而数字的单位是可变的?

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

How can I round up a number with decimals when the number unit varies?

问题

我想始终将其四舍五入为6位字符,例如:

  • 136.345987将成为136.346
  • 0.98765432将成为0.987654

我该如何做到这一点?

我尝试过使用round(),但它只适用于小数。而且我不太希望将其转换为字符串,所以是否有办法仅使用数字的字符来实现这一目标?

英文:

I want to make it possible to round up always 6 character, for example:

  • 136.345987 would be 136.346
  • 0.98765432 would be 0.987654

How can I do this?

I've tried with round(), but it only works for decimals. And not really interesed in passing it to strng,so is there any way to do this with the chars of the number?

答案1

得分: 1

以下是翻译好的部分:

文档链接: https://docs.python.org/3/library/functions.html#round

请注意,round函数接受多个参数。
代码:

round(number, ndigits=None)

返回四舍五入到小数点后ndigits位的数字。如果省略ndigits参数或将其设为None,它将返回其输入的最接近整数。

使用以下代码,我们可以通过减去小数点后数字的长度来确定我们要进行四舍五入的位置。

number = 11111.22
round_to = 3
number_string = str(number).split(".")

print(round_to - len(number_string[0]))

index_at = round_to - len(number_string[0])
print(round(number, index_at))

测试用例:
输入:

136.345987

输出:

3
136.346
英文:

Docs: https://docs.python.org/3/library/functions.html#round

Know that rounding takes multiple parameters.
Code:

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.

Using the following code, we can subtract the number we want to index (for rounding) by the length of the numbers behind the decimal space.

number = 11111.22
round_to = 3
number_string = str(number).split(".")

print(round_to-len(number_string[0]))

index_at = round_to-len(number_string[0])
print(round(number, index_at))

Test case:
Input:

136.345987

Output:

3
136.346

huangapple
  • 本文由 发表于 2023年2月23日 23:24:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75546865.html
匿名

发表评论

匿名网友

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

确定