JS Number相关

166 阅读1分钟

1 .保留两位小数,会四舍五入

保留0.00

const toDecimal2 = (x) => {
    let f = Math.round(x * 100) / 100;
    let s = f.toString();
    let rs = s.indexOf('.');
    if (rs < 0) {
        rs = s.length;
        s += '.';
    }
    while (s.length <= rs + 2) {
        s += '0';
    }
    return s;
}
toDecimal2(2) //2.00
toDecimal2(2.147) //2.15

不保留0.00

const toDecimal2NoZero=(x)=> {
    let f = Math.round(x * 100) / 100;
    let s = f.toString();
    return s;
}
toDecimal2NoZero(2.00) //2
toDecimal2NoZero(2.99) //2.99
toDecimal2NoZero(2.995)//3

2. 保留两位小数(不进行四舍五入)

保留0.00

const toDecimal2 = (x) => {
    let f = Math.floor(x * 100) / 100;
    let s = f.toString();
    let rs = s.indexOf('.');
    if (rs < 0) {
        rs = s.length;
        s += '.';
    }
    while (s.length <= rs + 2) {
        s += '0';
    }
    return s;
}
toDecimal2(2) //2.00
toDecimal2(2.147) //2.14

不保留0.00

const toDecimal2NoZero=(x)=> {
    let f = Math.floor(x * 100) / 100;
    let s = f.toString();
    return s;
}
toDecimal2NoZero(2.00) //2
toDecimal2NoZero(2.99) //2.99
toDecimal2NoZero(2.995)//2.99

3. 保留两位小数 如果小数后面都是0保留整数否则保留两位小数

const toDecimal2 = (x) => {
    if (typeof x == 'string') {
        //传入的数值包含文字 如46488元 正则匹配去除汉字
        x = x.replace(/[\u4e00-\u9fa5]/g, "")
    }
    let f = Math.floor(x * 100) / 100;
    let s = f.toString()
    let p = s.split('.')
    if (p.length == 1) return p[0]
    if (p.length > 1 && p[1].length < 2) {
        return p[0] + '.' + p[1].padEnd(2, '0')
    } else {
        return p[0] + '.' + p[1]
    }
}
toDecimal2(35123.00) //35123
toDecimal2(35123.1)  //35123.10
toDecimal2(35123.123)//35123.12