Skip to content

Instantly share code, notes, and snippets.

@kentyeh
Last active March 4, 2024 08:48
Show Gist options
  • Save kentyeh/941cd4061d88a769c8ac4d7e9ec106e1 to your computer and use it in GitHub Desktop.
Save kentyeh/941cd4061d88a769c8ac4d7e9ec106e1 to your computer and use it in GitHub Desktop.
數值轉中文大寫
import java.util.regex.Pattern;
/**
* @author Kent Yeh
*/
public class ZhBigNum {
public static final Pattern ZEROP = Pattern.compile("\\x{96F6}{2,}");
public static void main(String[] args) {
System.out.println(toZhBigNum("1002000304050"));
System.out.println(toZhBigNum("305000"));
System.out.println(toZhBigNum("100020003000"));
}
public static String toZhBigNum(String value) {
char[] bd = new char[]{'零', '壹', '貳', '參', '肆', '伍', '陸', '柒', '捌', '玖'};
String[] tail1 = new String[]{"", "拾", "佰", "仟"};
String[] tail2 = new String[]{"", "萬", "億", "兆"};
StringBuilder res = new StringBuilder();
int pos = 0;
boolean fnz = false;//每4個一組,直到碰到不是0才為true
for (char c : new StringBuilder(value).reverse().toString().toCharArray()) {
int d = c;
int r = pos / 4;
int m = pos % 4;
boolean nz = c > 48;
fnz = m == 0 ? c > 48 : c > 48 || fnz;
res.append(nz ? tail2[r] : "").append(nz ? tail1[m] : "").append(fnz ? bd[d - 48] : "");
if (nz) {
tail2[r] = "";
}
pos++;
}
return ZEROP.matcher(res.reverse().toString()).replaceAll("零");
}
public static String toZhBigNumFast(String value) {
char[] bd = new char[]{'零', '壹', '貳', '參', '肆', '伍', '陸', '柒', '捌', '玖'};
String[] tail1 = new String[]{"", "拾", "佰", "仟"};
String[] tail2 = new String[]{"", "萬", "億", "兆"};
StringBuilder res = new StringBuilder();
boolean fnz = false;//每4個一組,直到碰到不是0才為true
char[] cs = value.toCharArray();
int len = cs.length;
for (int i = len - 1; i > -1; i--) {
int d = cs[i];
int pos = len - i - 1;
int r = pos / 4;
int m = pos % 4;
boolean nz = d > 48;
fnz = m == 0 ? d > 48 : d > 48 || fnz;
res.append(nz ? tail2[r] : "").append(nz ? tail1[m] : "").append(fnz ? bd[d - 48] : "");
if (nz) {
tail2[r] = "";
}
}
return ZEROP.matcher(res.reverse().toString()).replaceAll("零");
}
}
function reverseString(str) {
return str.split('').reverse().join('');
}
function toZhBigNum(snum){
if(!snum||snum===0||snum==='零')
return '零';
snum = ''+snum;
let bd = ['零', '壹', '貳', '參', '肆', '伍', '陸', '柒', '捌', '玖'];
let tail1=['', '拾', '佰', '仟'];
let tail2=['', '萬', '億', '兆'];
let fnz = false;
let len = snum.length;
let res = '';
for (let i = len - 1; i > -1; i--) {
let d = snum.charCodeAt(i);
let pos = len - i - 1;
let r = Math.floor(pos / 4);
let m = pos % 4;
let nz = d > 48;
fnz = m == 0 ? d > 48 : d > 48 || fnz;
if(nz)
res = res + tail2[r] + tail1[m];
if(fnz){
res = res + bd[d - 48];
}
if(nz)
tail2[r] = '';
}
return reverseString(res).replace(/\u96F6{2,}/g, '零');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment