UNPKG

2.55 kBPlain TextView Raw
1const ONE = 'หนึ่ง'
2const TWO = 'สอง'
3const THREE_TO_NINE = ['สาม', 'สี่', 'ห้า', 'หก', 'เจ็ด', 'แปด', 'เก้า']
4const ED = 'เอ็ด'
5const YEE = 'ยี่'
6const LAN = 'ล้าน'
7const EMPTY = ''
8const DIGIT = [EMPTY, 'สิบ', 'ร้อย', 'พัน', 'หมื่น', 'แสน']
9const ONES = [EMPTY, ED, TWO, ...THREE_TO_NINE]
10const TENS = [EMPTY, ...[EMPTY, YEE, ...THREE_TO_NINE].map(t => t + DIGIT[1])]
11const SUB_HUNDRED = TENS.flatMap(t => ONES.map(o => t + o))
12SUB_HUNDRED[1] = ONE
13const SUB_TEN = [EMPTY, ONE, TWO, ...THREE_TO_NINE]
14
15function numberToWords(num: string): string {
16 let output = EMPTY
17 const length = num.length
18
19 for (let i = 0; i < length; i++) {
20 const d = num[i]
21 const di = length - i - 1
22 const diMod = di % 6
23 const isSib = diMod === 1
24 switch (d){
25 case '0':
26 break;
27 case '1':
28 if(isSib){output += DIGIT[diMod]}
29 else if(!diMod && i){output += ED}
30 else{output += SUB_TEN[Number(d)] + DIGIT[diMod]}
31 break;
32 default:
33 if(isSib && d === '2'){output += YEE + DIGIT[diMod]}
34 else{
35 output += SUB_TEN[Number(d)] + DIGIT[diMod]
36 }
37 break;
38 }
39 if (!diMod && di) {
40 output += LAN
41 }
42 }
43 return output
44}
45export default function bahtText(userInput: number | string): string | boolean {
46 let baht: number
47 let bahtStr: string
48 let satang: number
49 let isNegative = false
50 let input: number
51 if (typeof userInput === 'number') {
52 if(userInput >Number.MAX_SAFE_INTEGER)
53 return false
54 input = userInput
55 } else {
56 input = Number(userInput)
57 if (isNaN(input) || input >Number.MAX_SAFE_INTEGER){
58 return false
59 }
60 }
61 if (input < 0) {
62 isNegative = true
63 input = -input
64 }
65 satang = Number.isInteger(input) ? 0 : (Math.round(input%1 * 100))
66 baht = Number.isInteger(input) ? input :Math.floor(input)
67 if(satang>=100) {
68 baht++
69 satang%=100
70 }
71 bahtStr = '' + baht
72 if (!baht && !satang) {
73 return 'ศูนย์บาทถ้วน'
74 }
75
76 let output = isNegative ? 'ลบ' : EMPTY
77
78 // Baht
79 output += numberToWords(bahtStr)
80
81 // Satang
82 if (satang) {
83 if (baht) output += 'บาท'
84 // Faster!
85 output += SUB_HUNDRED[satang] + 'สตางค์'
86 // output += SUB_HUNDRED_FUNC(satang) + 'สตางค์'
87 // output += numberToWords(satang.toString()) + 'สตางค์';
88 } else {
89 output += 'บาทถ้วน'
90 }
91
92 return output
93}
\No newline at end of file