Python中使用round函数保存小数点任意位数
在Python编程中,如果要对一个浮点数进行四舍五入,可使用round函数来实现。round函数的语法以下:
```round(number[,ndigits])```其中,number是要进行四舍五入的数字,ndigits是保存的小数点位数。如果ndigits省略不填,默许保存到整数。下面分别介绍在Python中怎样使用round函数保存1到6位小数。
保存1位小数
要保存1位小数,只需把ndigits设置为1便可:
```num=3.1415926result=round(num,1)print(result)输出3.1```保存2位小数
要保存2位小数,只需把ndigits设置为2便可:
```num=3.1415926result=round(num,2)print(result)输出3.14```保存3位小数
要保存3位小数,只需把ndigits设置为3便可:
```num=3.1415926result=round(num,3)print(result)输出3.142```保存4位小数
要保存4位小数,只需把ndigits设置为4便可:
```num=3.1415926result=round(num,4)print(result)输出3.1416```保存5位小数
要保存5位小数,只需把ndigits设置为5便可:
```num=3.1415926result=round(num,5)print(result)输出3.14159```保存6位小数
要保存6位小数,只需把ndigits设置为6便可:
```num=3.1415926result=round(num,6)print(result)输出3.141593```通过以上方法,我们可以轻松实现在Python中保存小数点任意位数的功能。
桂&哥&网&络www.guIgEge.cn
TOP