java 怎么让输出结果2.0变成2 运算结果为:1.0 + 1.0 = 2.0

//做一个计算器
package homework;
import java.util.Scanner;
public class homework5 {
public static void main(String[] args) {
try {
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
System.out.println("计算器");
System.out.println("使用说明 1.加法 2.减法 3.乘法 4.除法");
for (double i = 0; i < 100; i++) {
System.out.print("\n请选择运算规则:");
int num = input.nextInt();
switch (num) {
case 1:
System.out.println("你选择了加法");
System.out.print("请输入第1个加数:");
double jiashu1 = input.nextDouble();
System.out.print("请输入第2个加数:");
double jiashu2 = input.nextDouble();
System.out.println("运算结果为:" + jiashu1 + " + " + jiashu2
+ " = " + (jiashu1 + jiashu2));
break;
case 2:
System.out.println("\n******你选择了减法******\n");
System.out.print("请输入被减数:");
double jianshu1 = input.nextDouble();
System.out.print("请输入减数:");
double jianshu2 = input.nextDouble();
System.out.printf("运算结果为:" + jianshu1 + " - " + jianshu2
+ " = " + (jianshu1 - jianshu2));
break;
case 3:
System.out.println("\n******你选择了乘法******\n");
System.out.print("请输入第1个因数:");
double chengfa1 = input.nextDouble();
System.out.print("请输入第2个因数:");
double chengfa2 = input.nextDouble();
System.out.printf("运算结果为:" + chengfa1 + " * " + chengfa2
+ " = " + (chengfa1 * chengfa2));
break;

default:
System.out.println("\n你的选择错误,请重新选择!");
break;
}
}
} catch (Exception e) {
System.out.print("请输入整数");
}
}
}

思路:

1,使用BigDecimal类里面的valueOf(doeble d)方法,

2,在使用BigDecimal类里面的stripTrailingZeros()方法,去除没用的0,

3,最后把BigDecimal类型转换为字符串,

4,注意,不能在把字符串转换为doule了,在转换为double前面的事情就白做了,

public class Demo11 {
public static void main(String[] args) {
double d1 = 2.0;
String s1 = BigDecimal.valueOf(d1).stripTrailingZeros().toPlainString();
System.out.println(s1);// 2

double d2 = 5.5;
String s2 = BigDecimal.valueOf(d2).stripTrailingZeros().toPlainString();
System.out.println(s2);// 5.5
}
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-09-04
static String fmt_prt_double( Double d ) //自定义格式化输出函数
    {
        String s=String.format("%f", d);//将浮点数转为字符串
        int i;
        for( i=s.length()-1;i>=0;i-- ) //从串尾向前检查,遇到非0数据结束循环
        {
            if ( s.charAt(i)=='.' ) //遇到小数点结束,说明是个整数
                break;
            if ( s.charAt(i) != '0' ) //遇到小数中有非0值,结束
            {
                i++;
                break;
            }
        }
        return s.substring(0,i); //返回处理后的子串
    }
    
    。。。
    System.out.println("运算结果为:" + jiashu1 + " + " + jiashu2
       + " = " + fmt_prt_double(jiashu1 + jiashu2));

本回答被提问者采纳
相似回答