Created
August 20, 2020 12:20
-
-
Save livoras/bac7c80120c48abbc6b4739d83fc9fe1 to your computer and use it in GitHub Desktop.
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
const nums = { | |
'零': 0, | |
'壹': 1, | |
'贰': 2, | |
'叁': 3, | |
'肆': 4, | |
'伍': 5, | |
'陆': 6, | |
'柒': 7, | |
'捌': 8, | |
'玖': 9, | |
} | |
const units = { | |
'拾': 10, | |
'佰': 100, | |
'仟': 1000, | |
'万': 10000, | |
'亿': 100000000, | |
'角': 0.1, | |
'分': 0.01, | |
'元': 1, | |
'整': 0, | |
} | |
const cnToNum = (cn: string): number => { | |
let num = 0 | |
cn = cn.replace(/\s/g, '') | |
let i = 0 | |
let isNum = false | |
let n = 0 | |
let sep = 0 | |
while (i < cn.length) { | |
const c = cn[i] | |
i++ | |
if (c in nums) { | |
n = nums[c] | |
if (n === 0) { | |
continue | |
} | |
if (isNum) { | |
throw new Error(`${cn[i - 1]} cannot after ${cn[i - 2]}`) | |
} | |
isNum = true | |
continue | |
} | |
if (!(c in units)) { | |
throw new Error('cannot found ' + c) | |
} | |
isNum = false | |
console.log(n, units[c], c) | |
if (units[c] === 0) { | |
continue | |
} | |
if (['万','亿','元','角','分'].includes(c)) { | |
sep += n | |
num = (num * 100 + (sep * units[c] * 100)) / 100 | |
sep = 0 | |
} else { | |
sep += n * units[c] | |
n = 0 | |
} | |
console.log(num) | |
} | |
return num | |
} | |
console.log(cnToNum('叁佰贰拾贰亿贰仟玖佰叁拾万零捌佰贰拾壹元贰角叁分')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment