All files / src/utils/Formatters NumberFormatter.js

12.5% Statements 4/32
8.57% Branches 3/35
33.33% Functions 1/3
12.5% Lines 4/32

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69        7x 7x 7x                                                                                                                     7x      
import Formatter from './Formatter';
 
export class NumberFormatter extends Formatter {
    constructor(pattern = '0', options) {
        super();
        this.pattern = pattern;
        this.options = options || {};
    }
 
    format(value, pattern) {
        pattern = pattern || this.pattern;
 
        if (typeof value !== 'number')
            return pattern.replace(/[0#.,]+/, value);
 
        const number = (pattern.match(/[0#.,]+/) || ['0'])[0];
        const parts = number.split('.');
        const fill = (parts[0].match(/0+$/) || ['0'])[0].length;
        const fixed = parts[1] ? parts[1].length : 0;
        const comma = pattern.includes(',');
 
        // 百分号
        if (this.options.percentSign) {
            value = value * 100;
        }
 
        value = value.toFixed(fixed).padStart(fixed ? fill + 1 + fixed : fill, '0');
        // 是否小数隐藏末尾0
        if (fixed > 0 && /#$/.test(parts[1])) {
            value = parseFloat(value) + ''; // 转字符串
        }
 
        if (comma) {
            const [interger, decimal] = value.split('.');
            value = interger.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
            if (decimal) {
                value = [value, decimal].join('.');
            }
        }
 
        // 百分号
        if (this.options.percentSign) {
            value += '%';
        }
 
        value = pattern.replace(/[0#.,]+/, value);
 
        return value;
    }
 
    parse(value, pattern) {
        pattern = pattern || this.pattern;
 
        let number = (String(value).match(/-?([0-9.,]+)/) || ['0'])[0];
 
        number = +number.replace(/,/g, '');
 
        if (this.options.percentSign && /%$/.test(value)) {
            number = number / 100;
        }
 
        return number;
    }
}
 
export const numberFormatter = new NumberFormatter();
 
export default NumberFormatter;