Easy Tutorial
❮ Programming En Cn Lua Table Length Analysis ❯

JavaScript Implementation for Converting Arabic Numerals to Chinese Capitalized Numbers

Category Programming Technology

Preparations Before Writing

Here are the key knowledge points needed for writing this method:

1. charAt(index): Returns the character at the specified position.

2. substr(start, length): Returns a string starting from a specified position with a specified length.

Parameters:

3. substring(start, end): Returns the specified substring.

Parameters:

Special Cases:

Specific Code

function ToString(n) {
    if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n)){
        return "Invalid data";  // Check if the data is greater than 0
    }

    var unit = "千百拾亿千百拾万千百拾元角分", str = "";
    n += "00";  

    var indexpoint = n.indexOf('.');  // If it's a decimal, capture the position before the decimal point

    if (indexpoint >= 0){
        n = n.substring(0, indexpoint) + n.substr(indexpoint+1, 2);   // If it's a decimal, capture the required unit
    }

    unit = unit.substr(unit.length - n.length);  // If it's an integer, capture the required unit
    for (var i=0; i < n.length; i++){
        str += "零壹贰叁肆伍陆柒捌玖".charAt(n.charAt(i)) + unit.charAt(i);  // Convert to capitalized numbers by iteration
    }

    return str.replace(/零(千|百|拾|角)/g, "零").replace(/(零)+/g, "零").replace(/零(万|亿|元)/g, "$1").replace(/(亿)万|壹(拾)/g, "$1$2").replace(/^元零?|零分/g, "").replace(/元$/g, "元整"); // Replace zero characters within the number to get the result
}

Online Testing

>

Author Nickname: Lichee荔枝

Author Email: [email protected]

❮ Programming En Cn Lua Table Length Analysis ❯