[英]How can I use an if statement to check if a number only has two digits after the decimal in java?
I'm currently only checking to see if a number is a float using this我目前只使用这个检查一个数字是否是一个浮点数
public boolean checkStringFloat(String str) {
try{
Float.parseFloat(str);
}
catch(NumberFormatException e){
return false;
}
return true;
}
but I want to use an if statement to check if it is a decimal with two digits.但我想使用 if 语句来检查它是否是带两位数的小数。 So for instance numbers like: 6.24, 5.28,13242.31, would be allowed but numbers like: 5.234, 1, 0, 4.235 would not be allowed.
因此,例如:6.24、5.28、13242.31 之类的数字是允许的,但 5.234、1、0、4.235 之类的数字是不允许的。 How can I do this?
我怎样才能做到这一点?
Split the string, and check the length of second part.拆分字符串,并检查第二部分的长度。
"13242.31".split( "\\." )[ 1 ].length() == 2
See this code run live at IdeOne.com .请参阅在 IdeOne.com 上实时运行的代码。
boolean hasTwoDigitDecimalFraction = "13242.31".split( "\\." )[ 1 ].length() == 2 ;
System.out.println( hasTwoDigitDecimalFraction ) ;
true
真的
Validate your inputs by calling String#contains
to be sure it has a FULL STOP character.通过调用
String#contains
来验证您的输入,以确保它有一个 FULL STOP 字符。 And check the length of the array from the .split
to be sure it has exactly two elements.并从
.split
检查数组的长度,以确保它正好有两个元素。
Be aware that in many parts of the world such inputs would use a COMMA rather than a FULL STOP character as the delimiter: 13242,31
.请注意,在世界许多地方,此类输入将使用逗号而不是句号作为分隔符:
13242,31
。
BigDecimal#scale
As @TimBiegeleisen said, use BigDecimal
with its scale
method.正如@TimBiegeleisen 所说,将
BigDecimal
与它的scale
方法一起使用。
public boolean checkStringFloat(String str) {
BigDecimal bigDecimal = new BigDecimal(str);
if(bigDecimal.scale() == 2) {
return true;
} else {
return false;
}
}
My general idea is as follows, just for reference Start with a simple end-to-zero operation on the string String indexOf('.') returns i, len= string.length and the following will happen:我的大致思路如下,仅供参考 对字符串String indexOf('.')进行简单的归零操作开始,返回i, len= string.length 会发生以下情况:
You could find the length of the string after the "."您可以在“。”之后找到字符串的长度。 using
.substring()
.使用
.substring()
。
if (str.substring(str.indexOf(".")).length() == 2) return true;
else return false;
I don't have an editor with me, but this should work fine.我没有编辑器,但这应该可以正常工作。 If it doesn't, try adding a 1 to the indexOf.
如果没有,请尝试将 1 添加到 indexOf。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.