Java-将数字转换成中文人名币

// 将数字转换成人名币
// 如12345.12读成一万两千三百四十五元一角两分
// 默认输入的是合法数字
// 暂时先处理小于一亿的数组
public class JavaArrayDemo {
  private static String[] chineseRMBArray = new String[]{"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
  private static String[] chineseRMBIntegerArray = new String[]{"万", "千", "百", "十"};
  private static String[] chineseRMBDecimalArray = new String[]{"角", "分"};
  public static void main(String[] args) {
    float f = 123456.123f;
    String result = getChineseRMBString(f);
    System.out.println(result);
  }

  public static String getChineseRMBString(Float rmbNumber) {
    String result = "";
    String rmbString = rmbNumber.toString();
    String[] strArr = rmbString.split("\\.");
    // 先处理整数位
    result += getChineseRMBStringBeforeDecimalPoint(strArr[0]);
    // 再处理小数位
    if (strArr[1].length() >= 3) {
      strArr[1] = strArr[1].substring(0, 2);
    }
    result = result + getChineseRMBStringAfterDecimalPoint(strArr[1]);
    return result;
  }

  private static int getIndexFromString(char c) {
    return Integer.parseInt(String.valueOf(c).toString());
  }

  public static String getChineseRMBStringAfterDecimalPoint(String decimalString) {
    String decimalResult = "";
    decimalResult = chineseRMBArray[getIndexFromString(decimalString.charAt(0))] + chineseRMBDecimalArray[0] + chineseRMBArray[getIndexFromString(decimalString.charAt(1))] + chineseRMBDecimalArray[1];
    return decimalResult;
  }

  public static String getChineseRMBStringBeforeDecimalPoint(String integerString) {
    String integerResult = "";
    int length = integerString.length();
    for (int i = length - 1; i >= 0; i--) {
      // 万
      if (i == 4) {
        integerResult += chineseRMBArray[getIndexFromString(integerString.charAt(5 - i))] + chineseRMBIntegerArray[0];
      }
      // 千
      if (i == 3 || i == 7) {
        integerResult += chineseRMBArray[getIndexFromString(integerString.charAt(5 - i))] + chineseRMBIntegerArray[1];
      }
      // 百
      if (i == 2 || i == 6) {
        integerResult += chineseRMBArray[getIndexFromString(integerString.charAt(5 - i))] + chineseRMBIntegerArray[2];
      }
      // 十
      if (i == 1 || i == 5) {
        integerResult += chineseRMBArray[getIndexFromString(integerString.charAt(5 - i))] + chineseRMBIntegerArray[3];
      }
      // 个
      if (i == 0) {
        integerResult += chineseRMBArray[getIndexFromString(integerString.charAt(5 - i))] + "元";
      }
    }
    return integerResult;
  }
}

你可能感兴趣的:(Java-将数字转换成中文人名币)