概述
四舍五入保留2位小数(不够位数,则用0替补)
function keepTwoDecimalFull(num) {
var result = parseFloat(num);
if (isNaN(result)) {
alert('传递参数错误,请检查!');
return false;
}
result = Math.round(num * 100) / 100;
var s_x = result.toString(); //将数字转换为字符串
var pos_decimal = s_x.indexOf('.'); //小数点的索引值
// 当整数时,pos_decimal=-1 自动补0
if (pos_decimal < 0) {
pos_decimal = s_x.length;
s_x += '.';
}
// 当数字的长度< 小数点索引+2时,补0
while (s_x.length <= pos_decimal + 2) {
s_x += '0';
}
return s_x;
}
console.log(keepTwoDecimalFull(120.5)); //120.50
console.log(typeof keepTwoDecimalFull(120.5)); //string
console.log(keepTwoDecimalFull(2.446242342)); //2.45
console.log(typeof keepTwoDecimalFull(2.446242342)); //string
感谢您的支持
最后
以上就是震动书本为你收集整理的js金额价格四舍五入保留2位小数demo效果(整理)的全部内容,希望文章能够帮你解决js金额价格四舍五入保留2位小数demo效果(整理)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复