取整
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