我试图让用户按照自己的风格自由输入数字,就像他可以选择输入 2 或 2.00 但如你所知, double 不能接受这个 (2)。我希望 double 仅接受小数点后两位(基本上我代表金钱)。 这就是我不确定如何获取输入并将其转换为 2decimals 格式的原因。 java.tks 新手
尝试过谷歌,但找不到我可以在输入本身进行格式化的地方,这意味着甚至不允许用户输入除2位小数之外的任何小数位,而不是在输入多个不同变量后进行后处理。,tks
public static void add()
{
double accbal;
Scanner sc = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("0.00");
System.out.println("Enter account balance");
accbal = sc.nextDouble();
//this is the part where i need to know the entered value is formated to only 2 decimal places
}
最佳答案
由于显示小数位对最终用户来说实际上是一种形式,因此您可以将值作为 String
读取,并将其转换为 Double
或 BigDecimal
,如果您处理实际财务问题,则首选后者。
相关:What Every Computer Scientist Should Know About Floating-Point Arithmetic
public static void add() {
BigDecimal accbal; // could declare a Decimal
Scanner sc = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("#.00");
System.out.println("Enter account balance");
accbal = new BigDecimal(sc.nextLine());
System.out.println(df.format(accbal.doubleValue()));
}
关于Java双输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12027900/