Last active
December 20, 2015 13:28
-
-
Save ssddi456/6138590 to your computer and use it in GitHub Desktop.
int to chiness
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function intToChinese (str) { | |
str = str + ''; | |
var len = str.length - 1; | |
var idxs = ['', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '万', '十', '百', '千', '亿']; | |
var num = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']; | |
return str.replace(/([1-9]|0+)/g, function($, $1, idx, full) { | |
var pos = 0; | |
if ($1[0] != '0') { | |
pos = len - idx; | |
if (idx == 0 && $1[0] == 1 && idxs[len - idx] == '十') { | |
return idxs[len - idx]; | |
} | |
return num[$1[0]] + idxs[len - idx]; | |
} else { | |
var left = len - idx; | |
var right = len - idx + $1.length; | |
if( left%4 == 0 && $1 == '0' ){ | |
return idxs[left]; | |
} | |
if (Math.floor(right / 4) - Math.floor(left / 4) > 0) { | |
pos = left - left % 4; | |
} | |
if (pos) { | |
return idxs[pos] + num[$1[0]]; | |
} else if (idx + $1.length >= len) { | |
return ''; | |
} else { | |
return num[$1[0]] | |
} | |
} | |
}); | |
} | |
console.log(intToChinese(13027)); | |
console.log(intToChinese(24985043)); | |
console.log(intToChinese(10003000)); | |
console.log(intToChinese(10003000200)); | |
console.log(intToChinese(1000000200)); | |
console.log(intToChinese(10101010)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment