js 取整,保留2位小数

取整

1 parseInt(string, radix)

解析一个字符串,并返回一个整数
当参数 radix 的值为 0,或没有设置该参数时,parseInt() 会根据 string 来判断数字的基数。
如果 string 以 “0x” 开头,parseInt() 会把 string 的其余部分解析为十六进制的整数。
如果 string 以 1 ~ 9 的数字开头,parseInt() 将把它解析为十进制的整数。

parseInt(1.56) //1
parseInt("1.56") // 1
parseInt(0x12) // 18
parseInt("0x12") // 18
parseInt(-1.5) // -1
parseInt("abc") // NaN
parseInt(12, 10) // 12
parseInt(12.4, 10) // 12
parseInt(12, 16) // 18
parseInt(12.4, 16) // 18
2 Math.round(num)

四舍五入取整,(5时向上取整)

Math.round(12) // 12
Math.round("12") // 12

Math.round(12.4) // 12
Math.round(12.5) // 13
Math.round("12.5") // 13

Math.round(-12.5) //-12
Math.round(-12.6) // -13
3 Math.ceil(num)

向上取整

Math.ceil(12) // 12
Math.ceil("12") // 12

Math.ceil(12.4) // 13
Math.ceil(12.5) // 13
Math.ceil("12.5") // 13

Math.ceil(-12.5) // -12
Math.ceil(-12.6) // -12
4 Math.floor

向下取整

Math.floor(12) // 12
Math.floor("12") // 12

Math.floor(12.4) // 12
Math.floor(12.5) //12
Math.floor("12.5") // 12

Math.floor(-12.5) // -13
Math.floor(-12.6) // -13

保留2位小数

1 num.toFixed(x)

把数字转换为字符串,结果的小数点后有指定位数的数字,四舍五入

(1.55555).toFixed(2)   // '1.56'
(1.5).toFixed(2)   // '1.50'
2 借用Math.floor()/Math.round
Math.floor(1.55555 * 100) / 100   // 1.55
Math.floor(1.5 * 100) / 100   // 1.5

Math.round(1.55555 * 100) / 100  //1.56
Math.round(1.5 * 100) / 100   //1.5
3 借用字符串匹配
Number((1.55555).toString().match(/^\d+(?:\.\d{0,2})?/))   // 1.55
Number((1.5).toString().match(/^\d+(?:\.\d{0,2})?/))   // 1.5

^:匹配输入字符串的开始位置
\d:匹配一个数字字符
+:匹配前面的子表达式一次或多次
(pattern):匹配 pattern 并获取这一匹配。所获取的匹配可以从产生的 Matches 集合得到
(?:pattern):匹配 pattern 但不获取匹配结果,也就是说这是一个非获取匹配,不进行存储供以后使用。
\.:匹配小数点
{n,m}:最少匹配 n 次且最多匹配 m 次,在逗号和两个数之间不能有空格
\d{n,m}:最少匹配 n 次最多匹配 m 次个数字字符
?:匹配前面的子表达式零次或一次

附:"1.55555".match(/^\d+(\.\d{0,2})?/)会有两个结果,1.55.55

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值