四舍五入保留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效果(整理)内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复