import java.text.DecimalFormat;
import java.util.Scanner;
public class Test{
public static void main(String[] args) {
System.out.println("请输入浮点数,输入负数结束:");
Scanner sc = new Scanner(System.in);
float[] num = new float[100];
for(int i=0;;i++){
num[i] = sc.nextFloat();
if(num[i]<0){
break;
}
Money money = new Money(num[i]);
String str = money.toString(num[i]);
System.out.println(str);
}
}
}
class Money{
int yuan,jiao,fen;
public Money(float x) {
this.yuan=yuan;
this.jiao=jiao;
this.fen=fen;
}
public String toString(float x ) {
DecimalFormat format = new DecimalFormat("0.##");
x = Float.valueOf(format.format(x));
String a = String.valueOf(x);
String[] b = a.split("\\.");
this.yuan = Integer.valueOf(b[0]);
Integer c = Integer.valueOf(b[1]);
if(c<10){
this.jiao = c;
this.fen =0;
return yuan+"元"+jiao+"角"+"0分";
}else if(c==0){
return yuan+"元"+"0角"+"0分";
}else{
this.fen = c%10;
this.jiao = c/10;
return yuan+"元"+jiao+"角"+fen+"分";
}
}
}
控制台打印结果:
请输入浮点数,输入负数结束:
3.12 5.4 122.39 666.66 1092.54 -1 23.2
3元1角2分
5元4角0分
122元3角9分
666元6角6分
1092元5角4分