保留n位小数
vue 保留n位小数语法示例今日需求
python 保留n位小数源码示例
vue 保留n位小数
语法
number.toFixed(x)
x 为必须参数 是 0 ~ 20 之间的值,包括 0 和 20,如果省略,将用 0 代替。
number 必须为数字或浮点数, 如若不是 可以使用parseFloat 转一下类型
返回值为 String 类型
自动做四舍五入
示例
a
= 1.53849
1.53849
a
.toFixed()
"2"
a
.toFixed(1)
"1.5"
a
.toFixed(2)
"1.54"
a
.toFixed(3)
"1.538"
b
= '14.82519'
"14.82519"
parseFloat(b
).toFixed()
"15"
parseFloat(b
).toFixed(1)
"14.8"
parseFloat(b
).toFixed(2)
"14.83"
parseFloat(b
).toFixed(3)
"14.825"
今日需求
将秒改为小时, 保留一位小数并四舍五入 操作如下
time
= '52056'
"52056"
Number
= parseInt(time
) / 3600
14.46
Number
.toFixed(1)
"14.5"
python 保留n位小数
源码
def round(number
, ndigits
=None):
"""
round(number[, ndigits]) -> number
# 将数字四舍五入到以十进制数字表示的给定精度(默认为0位)
Round a number to a given precision in decimal digits (default 0 digits).
This returns an int when called with one argument, otherwise the
same type as the number. ndigits may be negative.
"""
return 0
示例
a
= 1.358
b
= 1.711
c
= 2.222
d
= 6.00
print(round(a
,2), round(b
,1), round(c
,3), round(d
))
1.36 1.7 2.222 6
round(2.5)
2
round(2.51)
3
round(3.5)
4