您的位置:首页 > 移动开发 > 微信开发

Java小程序——将浮点数转换成人民币读法

2016-02-23 19:38 399 查看
自己在学习的过程中,根据书上部分知识,将此问题扩展而成;只是刚开始学习Java,编写的可能有些繁琐,还有divide的小功能没有实现。


import java.util.Arrays;
import java.io.*;
//将浮点数拆分时,11.034这类无法正确显示
public class Num2Rmb
{
private String[] Num={"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
private String[] Unit={"","十","百","千"};
private String[] Another=new String[]{"亿","万","元","角","分"};
/*
*@parameter 输入的一个数字
*@return    返回将数字分成整数部分和小数部分
*/
public String[] divide(double iptStr)
{
long zheng=(long)(iptStr);
long xiao=Math.round((iptStr-zheng)*100);
return new String[] {zheng+"",String.valueOf(xiao)};
}

/*将一个四位数转换成中文字符
*@parameter String num
*@return    读法
*/
public String trans(String num,String num2)
{
String result="";
int numLen=num.length();

int zhengLen=numLen/4;
int yuLen=numLen%4;
int count=0;

for(int i=0;i<numLen;i++)
{
int a=num.charAt(i)-48;
if(i<yuLen)
{
if(a!=0&&(i+5-yuLen)%4!=0)
{
result+=Num[a]+Unit[yuLen-1-i];
}
else
{
if(a==0)
{
result+=Num[a];
}
else
{
count++;
result+=Num[a]+Another[(5+count-zhengLen)%4];
}
}
}
else
{
if(yuLen!=0)
{
if(a!=0&&(i+5-yuLen)%4!=0)
{
result+=Num[a]+Unit[3-(i-yuLen)%4];
}
else
{
if(a==0)
{
result+=Num[a];
}
else
{
count++;
result+=Num[a]+Another[(5+count-zhengLen)%4];
}
}
}
else
{
if(a!=0&&(i+5-yuLen)%4!=0)
{
result+=Num[a]+Unit[3-(i-yuLen)%4];
}
else
{
if(a==0)
{
result+=Num[a];
}
else
{
count++;
result+=Num[a]+Another[(6+count-zhengLen)%4];
}
}
}
}
}
for(int j=0;j<num2.length();j++)
{
int b=num2.charAt(j)-48;
if(b!=0)
{
result+=Num[b]+Another[3+j];
}
else
{
result+=Num[b];
}
}
return result;
}
public static void main(String[] args) throws Exception
{
//必须在main函数那一行throws Exception才行
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str=null;
System.out.println("请输入一个你要转换的数字:");
str=br.readLine();
double ip=Double.parseDouble(str);

Num2Rmb test=new Num2Rmb();
int strLen=test.divide(ip)[0].length();
if(strLen>12||ip<10e-8)
{
System.out.println("ERROR!Please reinput a num within 12 position...(Not a negative number!)");
return;
}
System.out.println(Arrays.toString(test.divide(ip)));

4000
System.out.println(test.trans(test.divide(ip)[0],test.divide(ip)[1]));
}
}


“`
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java