人民币转换

package oj.test;

import java.util.Arrays;
import java.util.Scanner;

public class Demo1 {
 
 public static final char[] chNumSet = "零壹贰叁肆伍陆柒捌玖".toCharArray();
 public static final char[] chPowSet = "分角元拾佰仟万拾佰仟亿拾佰仟万".toCharArray();
/*
 *人民币转换
 *1、中文大写金额数字前应标明“人民币”字样。中文大写金额数字应用壹、贰、叁、肆、伍、陆、柒、捌、玖、拾、佰、仟、万、亿、元、
 *角、分、零、整等字样填写。(30分)
 *2、中文大写金额数字到“元”为止的,在“元”之后,应写“整字,如¥ 532.00应写成“人民币伍佰叁拾贰元整”。在”角“和”分“后面不
 *写”整字。(30分)
 *3、阿拉伯数字中间有“0”时,中文大写要写“零”字,阿拉伯数字中间连续有几个“0”时,中文大写金额中间只写一个“零”字,
 *如¥6007.14,应写成“人民币陆仟零柒元壹角肆分“。
 */
 public static void main(String[] args) { 
  go();
 }

 private static void go() {
  //读入一个数值
  Scanner sc = new Scanner(System.in);
  while(sc.hasNext()){
   double d = sc.nextDouble();
   //解析该数值为汉字形式
   long l = (long)(d*100);
   String strRes = parse(l);
   System.out.println( "人民币"+strRes );
  }
 }

 private static String parse(long n) {
  if(n==0){
   return "零元整";
  }
  StringBuilder sb  = new StringBuilder();
  //将数值解析为单个数值的数组
  int[] nums = toNum( n );
  for( int i = nums.length-1; i >= 0; i-- ) {
   sb.append(chNumSet[nums[i]]);   
   sb.append(chPowSet[i]);
  }
  String res = sb.toString().
    replaceAll("零[分角拾佰仟]", "零").
    replaceAll("零+", "零").
    replaceAll("零+元", "元").    
    replaceAll("零+万", "万").
    replaceAll("零+亿", "亿").
    replaceAll("亿万", "亿");    
  if( res.startsWith("壹拾")  )
  {
   res = res.substring(1);
  }
  if(res.endsWith("零"))
  {
   res = res.substring(0, res.length()-1);
  }
  if(res.endsWith("元")){
   res = res + "整";
  }
  return res;
 }

 private static int[] toNum(long n) {
  int[] res = new int[0];
  while( n != 0 ){
   int end = (int) (n % 10L);
   //扩展数组的长度
   res = Arrays.copyOf(res, res.length+1);
   res[res.length-1] = end;
   n /= 10L;
  }
  return res;
 }

 public static void sop(Object o){
  System.out.println(o);
 }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值