Java: 我想得到双数据类型的整数输出
Java: I want to get an Integer output in double datatype
class simple {
public static void main() {
double n, m;
Scanner ip = new Scanner(System.in);
n = ip.nextDouble();
m = ip.nextDouble();
m = n * m;
System.out.println("Value in " + m);
}
}
在上面的代码中..
如果我的输入使用小数点,我的输出应该只使用小数点,其余时间它应该像整数一样打印。
例如:INPUT : 2 , 3
--> OUTPUT : Value is 6
INPUT : 2.1, 1
--> OUTPUT : Value is 2.1
所以我的问题是....我如何根据我的输入打印我的数字(带小数点,不带小数点)?
使用 Math.round() (http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#round(double)) 对输出进行四舍五入!
可以使用NumberFormat
; # 符号表示小数仅在非零时显示。
System.out.println("Value in " + new DecimalFormat("0.########").format(m));
double n1,n2,n3,checkdecimal;
n3=n1*n2;
checkdecimal = n3 - Math.floor(n3);
if(checkdecimal == 0)
screen.setText(new DecimalFormat("0.#").format(this.Answer) + ""); // It will print without decimal point
else
screen.setText(this.Answer +""); // It will print with decimal point
最后我自己找到了解决方案...
class simple {
public static void main() {
double n, m;
Scanner ip = new Scanner(System.in);
n = ip.nextDouble();
m = ip.nextDouble();
m = n * m;
System.out.println("Value in " + m);
}
}
在上面的代码中.. 如果我的输入使用小数点,我的输出应该只使用小数点,其余时间它应该像整数一样打印。
例如:INPUT : 2 , 3
--> OUTPUT : Value is 6
INPUT : 2.1, 1
--> OUTPUT : Value is 2.1
所以我的问题是....我如何根据我的输入打印我的数字(带小数点,不带小数点)?
使用 Math.round() (http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#round(double)) 对输出进行四舍五入!
可以使用NumberFormat
; # 符号表示小数仅在非零时显示。
System.out.println("Value in " + new DecimalFormat("0.########").format(m));
double n1,n2,n3,checkdecimal;
n3=n1*n2;
checkdecimal = n3 - Math.floor(n3);
if(checkdecimal == 0)
screen.setText(new DecimalFormat("0.#").format(this.Answer) + ""); // It will print without decimal point
else
screen.setText(this.Answer +""); // It will print with decimal point
最后我自己找到了解决方案...