format.js
export function formatFloat(num, n = 2) {
let f = parseFloat(num);
if (isNaN(f)) return false;
f = Math.round(num * Math.pow(10, n)) / Math.pow(10, n); // floor 舍 round 四舍五入 ceil 入
let s = f.toString();
let rs = s.indexOf('.');
//判定如果是整数,增加小数点再补0
if (rs < 0) {
rs = s.length;
s += '.';
}
while (s.length <= rs + n) {
s += '0';
}
return s;
}
使用
import {
formatFloat
} from '../utils/format.js'
mounted(){
let aa = 0.1455
console.log('aaaaaaaa', this.getRate(aa)) // 14.6
},
methods: {
getRate(num) {
return parseFloat(formatFloat(num * 100)).toFixed(1)
}
}