Skip to content

getDecimalLength

获取数字的小数位数

配置项

参数类型是否必选默认值参数描述
numnumber | number[]-输入的数字或数字数组

返回值

类型描述
number | number[]小数位数或小数位数数组

示例

getDecimalLength(123) // 输出: 0
getDecimalLength(123.456) // 输出: 3
getDecimalLength(1.23e-10)// 输出: 12
getDecimalLength(1.23e10) // 输出: 0
// 数组输入
getDecimalLength([123, 123.456, 0.123456789, 1.23e-10, 1.23e10]) // 输出: [0, 3, 9, 12, 0]
// 错误输入
getDecimalLength('abc') // 抛出错误: 输入必须是一个有效的数字

源码

js
export function getDecimalLength (num) {
    function  getSingleDecimalLength (n) {
        if (typeof n !== 'number' || isNaN(n)) {
            throw new TypeError('输入必须是一个有效的数字');
        }

        // 将数字转换为字符串,支持科学计数法
        const str = n.toString();

        // 处理科学计数法
        if (str.includes('e')) {
            const [base, exponent] = str.split('e');
            const baseDecimalLength = base.includes('.') ? base.split('.')[1].length : 0;
            const exponentValue = parseInt(exponent, 10);
            return Math.max(0, baseDecimalLength - exponentValue);
        }

        // 查找小数点位置
        const decimalIndex = str.indexOf('.');

        // 返回小数位数
        return decimalIndex === -1 ? 0 : str.length - decimalIndex - 1;
    };

    // 处理数组输入
    if (Array.isArray(num)) {
        return num.map(getSingleDecimalLength);
    }
    // 处理单个数字输入
    return getSingleDecimalLength(num);
}