我需要使用java写一个工具类浮点金额转换为美元大写金额
以下是一个Java工具类,可以将浮点金额转换为美元大写金额:
import java.math.BigDecimal;
public class MoneyUtils {
private static final String[] ONES = { "", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine ", "Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen " };
private static final String[] TENS = { "", "", "Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety " };
private static final String[] THOUSANDS = { "", "Thousand ", "Million ", "Billion " };
private static final BigDecimal MAX_VALUE = new BigDecimal("999999999999.99");
public static String toWords(BigDecimal number) {
if (number.compareTo(BigDecimal.ZERO) == 0) {
return "Zero Dollars";
}
if (number.compareTo(MAX_VALUE) > 0) {
throw new IllegalArgumentException("Value exceeds maximum value of 999,999,999,999.99");
}
StringBuilder sb = new StringBuilder();
String[] parts = number.setScale(2, BigDecimal.ROUND_HALF_UP).toString().split("\\.");
String dollars = parts[0];
String cents = parts[1];
int thousandsIndex = 0;
while (dollars.length() > 0) {
int endIndex = Math.max(dollars.length() - 3, 0);
String chunk = dollars.substring(endIndex);
dollars = dollars.substring(0, endIndex);
int value = Integer.parseInt(chunk);
if (value > 0) {
sb.insert(0, THOUSANDS[thousandsIndex]);
sb.insert(0, toWords(value));
}
thousandsIndex++;
}
sb.append("Dollars");
if (!cents.equals("00")) {
sb.append(" and ");
sb.append(toWords(Integer.parseInt(cents)));
sb.append("Cents");
}
return sb.toString().trim();
}
private static String toWords(int number) {
StringBuilder sb = new StringBuilder();
if (number >= 100) {
int hundreds = number / 100;
sb.append(ONES[hundreds]);
sb.append("Hundred ");
number %= 100;
}
if (number >= 20) {
int tens = number / 10;
sb.append(TENS[tens]);
number %= 10;
}
if (number > 0) {
sb.append(ONES[number]);
}
return sb.toString();
}
}
使用示例:
BigDecimal amount = new BigDecimal("1234567.89");
String words = MoneyUtils.toWords(amount);
System.out.println(words); // "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven Dollars and Eighty Nine Cents"
原文地址: https://www.cveoy.top/t/topic/bZsy 著作权归作者所有。请勿转载和采集!