Java 验证双精度数是否包含 2 个小数位的简单方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21825862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:54:26  来源:igfitidea点击:

What is a simple way to validate if a double that contains 2 decimal places?

java

提问by user676567

I'm looking for an example in Java to check if a double amount entered by a user contains 2 decimal places e.g. 99.99 entered would return valid and 99.9 or 99.999 entered would return invalid.

我正在寻找一个 Java 示例来检查用户输入的双倍金额是否包含 2 个小数位,例如输入 99.99 将返回有效,而输入 99.9 或 99.999 将返回无效。

回答by Abimaran Kugathasan

Try the following regex

试试下面的正则表达式

\d+(\.\d{2})?

回答by Harsh Goswami

Double d = 234.12413;
String[] splitter = d.toString().split("\.");
splitter[0].length();   // Before Decimal Count
int decimalLength = splitter[1].length();  // After Decimal Count

if (decimalLength == 2)
   // valid
else
   // invalid

For Henry's question

对于亨利的问题

double d1 = 0.50;
double d2 = d1%1;
DecimalFormat df = new DecimalFormat("#.00");

int decimalLength = (df.format(d2).length()-1);

if (decimalLength == 2)
   //valid
else
   // invalid

Note : df.format(d2)returns .50, so the lengthis 3

注意:df.format(d2)返回.50,所以长度3

回答by Ashot Karakhanyan

One more approach:

另一种方法:

//assert that the string is valid number
String num = "99.99";  // I assume that is `String` because entered by user and not yet converted to `double`
int i = num.lastIndexOf('.');
if(i != -1 && num.substring(i + 1).length() == 2) {
    System.out.println("The number " + num + " has two digits after dot");
}

*ADDED If you wand use local specific decimal separatoruse the result of following expession instead of '.'.

*添加如果你想使用本地特定的decimal separator使用以下表达式的结果而不是'.'.

DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance();
DecimalFormatSymbols symbols = format.getDecimalFormatSymbols();
//symbols.getDecimalSeparator() == '.';