要求檢查數字的位數是否小於7位,在這種情況下插入數據庫否則不要。我曾嘗試以下解決方案:如何檢查BigDecimal中的位數?
解決方案一:
public static void checkNoOfDigitVal(BigDecimal bigDecVal) {
BigInteger digits = bigDecVal.toBigInteger();
BigInteger ten = BigInteger.valueOf(10);
int count = 0;
do {
digits = digits.divide(ten);
count++;
} while (!digits.equals(BigInteger.ZERO));
System.out.println("Number of digits : " + count);
}
首先解決工作正常,但有時有時while循環不滿足條件,並將不斷增加,導致無休止的計數計數。
第二溶液:
public static void checkNoOfDigitsVal(BigDecimal bigDecVal) {
String string = bigDecVal.toString();
String[] splitedString = string.split("\\.");
String[] newVal = splitedString[0].split("");
int a = newVal.length - 1;
if (a <= 6) {
System.out.println("correct size insert into DB: " + a);
} else {
System.out.println("Incorrect size insert cancel: " + a);
}
}
例如,如果該值爲999999.9999
,第二溶液將返回newVal.length = 6
。
請建議一個更好的解決方案來檢查循環開銷可以最小化的十進制數的位數。
如果會發生什麼你做這個? while(!digits.compareTo(BigInteger.ZERO)!= 0);'。 –
*「第二個解決方案將返回newVal.length = 7,而不是它應該是6,這是不正確的」* Huh? 6是否正確? –
可能的重複http://stackoverflow.com/questions/2296110/determine-number-of-decimal-place-using-bigdecimal – KERiii