英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论