java数字转中文金额
时间: 2024-06-12 12:08:21 浏览: 121
以下是Java实现中文金额的示例代码:
```
public static String numberToChinese(double number) {
String[] units = new String[]{"", "万", "亿", "万亿"};
String[] nums = new String[]{"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
String[] cents = new String[]{"角", "分"};
long temp = Math.round(number * 100);
int numIndex = 0;
int unitIndex = units.length - 1;
boolean isZero = true;
StringBuilder builder = new StringBuilder();
while (temp != 0) {
int digit = (int) (temp % 10);
if (digit != 0) {
builder.insert(0, units[unitIndex]);
builder.insert(0, nums[digit]);
isZero = false;
} else {
if (!isZero) {
builder.insert(0, nums[digit]);
}
isZero = true;
}
temp /= 10;
numIndex++;
if (numIndex % 4 == 0) {
unitIndex--;
}
}
if (builder.length() == 0) {
builder.append(nums[0]);
}
builder.append("元");
temp = Math.round(number * 100);
int centIndex = 0;
while (temp != 0 && centIndex < cents.length) {
int digit = (int) (temp % 10);
if (digit != 0) {
builder.append(nums[digit]).append(cents[centIndex]);
}
temp /= 10;
centIndex++;
}
if (builder.length() == 1) {
builder.append(nums[0]).append("角");
}
return builder.toString();
}
```
示例调用:
```
System.out.println(numberToChinese(123456789.12)); // 输出:壹亿贰仟叁佰肆拾伍万陆仟柒佰捌拾玖元壹角贰分
```
代码说明:
该实现将数字按照“亿、万、个”的单位进行分组,然后将每组的数字转成中文表示。在转换过程中,将0省略,同时在每个数字后面添加相应的单位。最后将整数部分和小数部分拼接起来,返回中文金额的字符串表示。
阅读全文