代码说明:
传入两个必传参数,第一个参数为需要传入的数值,第二个参数为小数点后有几位数
/**
* 保留n位小数,四舍五入
* @param {Number} _m_ 原始数字
* @param {Number} _n_ 保留n位,默认2位
* @returns
*/
function fixed(_m_, _n_ = 2){
const num = Number(_m_),
n = Number(_n_);
return num.toFixed(n)
// 或者
// Number.prototype.toFixed.call(num,n)
}
// 保留n位小数,向下取整
function fixedFloor(_m_, _n_ = 2) {
let num = Number(_m_);
const n = Number(_n_);
if (!isNaN(num) && !isNaN(n)) {
const multiple = 10 ** n;
num = Math.floor(num * multiple) / multiple;
let str = num.toString();
let index = str.indexOf(".");
if (index < 0) {
index = str.length; // 标记小数点位置
str += ".";
}
while (str.length <= index + n) {
str += "0";
}
return str;
}
return "0.00";
}
function fixedUp(_m_, _n_ = 2) {
let num = Number(_m_);
const n = Number(_n_);
if (!isNaN(num) && !isNaN(n)) {
const list = [...Math.floor(num * 10 ** n).toString()];
list.splice(-n, 0, ".");
return list.join("");
}
return "0.00";
}
提示:本文图片等素材来源于网络,若有侵权,请发邮件至邮箱:810665436@qq.com联系笔者删除。
笔者:苦海