将数字金额转换为文字表示的java代码
- User
将数字金额转换为文字表示的java代码
- Assistant
以下是将数字金额转换为文字表示的Java代码示例:
- User
将数字金额转换为中文文字表示的java代码
- Assistant
以下是将数字金额转换为中文文字表示的Java代码示例:
public class NumberToChineseConverter { private final static String[] nums = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"}; private final static String[] units = {"", "拾", "佰", "仟"}; private final static String[] largeUnits = {"", "万", "亿"}; public String convert(int number) { // check for zero or negative input if (number == 0) { return nums[0]; } else if (number < 0) { return "负" + convert(Math.abs(number)); } String word = ""; int unitIndex = 0; // convert each four digits of the number at a time while (number > 0) { int fourDigits = number % 10000; if (fourDigits > 0) { String subWord = convertLessThanTenThousand(fourDigits); word = subWord + largeUnits[unitIndex] + word; } number /= 10000; unitIndex++; } return word; } private String convertLessThanTenThousand(int number) { String word = ""; int unitIndex = 0; //convert each digit of the four digit number while (number > 0) { int digit = number % 10; if (digit > 0) { word = nums[digit] + units[unitIndex] + word; } number /= 10; unitIndex++; } //remove trailing zeroes while (word.endsWith(nums[0])) { word = word.substring(0, word.length() - 1); } return word; } public static void main(String[] args) { NumberToChineseConverter converter = new NumberToChineseConverter(); System.out.println(converter.convert(123456789)); } }