[英]How to limit decimals digits?
I am doing a basic calculator using double, but I wanted the output to limit on showing only 2 decimal digits.我正在使用 double 进行基本计算器,但我希望 output 限制仅显示 2 个十进制数字。
For example, when this is the input:例如,当这是输入时:
5 + 0.70
I wanted the output to be:我希望 output 是:
5.70
So how to do it so it always shows 2 decimal digits?那么如何做到这一点,它总是显示 2 个十进制数字? Below is my code:
下面是我的代码:
import java.util.Scanner;
class Main{
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
double fnum,snum,ans;
char sign;
fnum=input.nextDouble();
sign=input.next().charAt(0);
snum=input.nextDouble();
if (sign == '+' ){
ans=fnum + snum;
System.out.println(ans);
}
else if(sign == '-')
{
ans=fnum-snum;
System.out.println(ans);
}
else if(sign == '/'){
ans=fnum/snum;
System.out.println(ans);
}
else if(sign == '*'){
ans=fnum*snum;
System.out.println(ans);
}
else
System.out.println("Your Input is not correct,please check it for any error(s).");
}
}
Just use String.format:只需使用 String.format:
System.out.println(String.format("%.2f",ans));
Note that this converts your value into a String, for calculations you should keep using its numeric representation.请注意,这会将您的值转换为字符串,对于计算,您应该继续使用其数字表示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.