Skip to content
On this page

Math 数学方法

通用的一些数学方法是有精度问题的,所以这里做了一个统一的处理,防止精度丢失。

plus 数字相加

js
plus(0.1, 0.2)  // 0.3
plus(0.1, 0.2, 0.4)  // 0.7

minus 数字相减

js
minus(1, 0.2)  // 0.8
minus(1, 0.2, 0.4)  // 0.4

times 数字相乘

js
times(0.2, 0.2)  // 0.04
times(1, 0.2, 0.4)  // 0.08

div 数字相除

js
div(3, 2)  // 1.5
div(6, 3, 2)  // 1

toFixed 设置精度

js
toFixed(3.152254, 4)  // 3.1523

toString 设置精度

js
toString(3.152254)  // '3.152254'

round 四舍五入

js
round(3.152254, 1)  // '3.2'

sqrt 平方根

js
round(0.04)  // '0.2'

mod 相除的余数

js
mod(4, 3)  // 1

pow 次方运算

js
pow(2, 3)  // 8

thousands 转为千分位

js
thousands('123123123331234.556352', 2)  // 123,123,123,331,234.56

formatNumber 格式化数字

js
/**
 * 格式化数字
 * @param text 需要格式化的数字
 * @param pipes '2' 格式化需要保留几位小数
 *              '0.1-3' 代表小数点保留1-3位
 */
formatNumber('14.556352', '3')  // 14.556

formatNumber('1.53', '0.1-3')  // 1.53
formatNumber('1.5345', '0.1-3')  // 1.535
formatNumber('1', '0.1-3')  // 1.0