我如何使浮点数仅显示一定数量的小数 [英] How do I make a float only show a certain amount of decimals

查看:117
本文介绍了我如何使浮点数仅显示一定数量的小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个浮点数,该浮点数具有16个小数位,但是我希望将其限制为6,如果我得到的浮点数小于6个小数,我希望它加0直到它具有6. 即:

I have a float that has 16 decimal places, but I want it to be capped at 6, and if I ever get a float that has less than 6 decimals, I want it to add 0s until it has 6. i.e.:

1.95384240549 = 1.953842 3.12 = 3.120000

1.95384240549 = 1.953842 3.12 = 3.120000

我正在尝试根据对象的特定需求量生成一个值.谢谢!

I'm trying to generate a value based on a certain amount of demand an object has. Thanks!

推荐答案

要舍入到小数位数,可以使用round()

To round to a certain amount of decimals you can use round()

round(1.95384240549,6) > 1.953842

对于小数点后的更多0,可以使用format():

And for more 0's after the decimal place you can use format():

format(3.12, '.6f') > '3.120000'

请注意,这是字符串类型

在此处了解更多信息

舍入语法

格式语法

这篇关于我如何使浮点数仅显示一定数量的小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆