JavaScript JS 保留n位小数 去除无效零 可以不要四舍五入 ....

有时候我们要算一个特殊值

比如 

a=155005;

需要求 a 是多少万元....保留3位小数,且去除无效0...

字符串循环很累...

有个比较简单的操作

let result = a / 10000;
result = parseFloat( result.toFixed(3) ).toString() + "万元";

// result = "15.501万元"  (当然会四舍五入啦...你要想不四舍五入的话看下面)

// ----------不要四舍五入---------(诶需求辣么多...真烦)
result = a / 10000;
// 多留一位小数
result = parseFloat(result.toFixed(4)).toString();
// 如果位数符合长度,就切掉最后一位  ||  当然位数不足那就不切啦...
result = result.length >4 ? 
            (parseFloat(result.substring(result.length - 1, 0)) + "万元") : 
            (result + "万元");
// result = "15.5万元"  

好吧希望有用...我接着写项目了

猜你喜欢

转载自blog.csdn.net/ljason1993/article/details/89553276
今日推荐