eee的答案更加清晰,並且幾乎可以一路獲得。但是,我確實要求數字位數(不包括可選小數點)始終小於給定數字(比如5)。
這包括任何領先的0.
爲完全小數。
所以:
Input: 0.111111 Output: 0.11111
太長,需要進行:
Input: 0.111111 Output: 0.1111
這種方法是優雅的要少得多,但更具體的關於保障的最終長度字符串。
我已經在這裏發佈了它,因爲它可能是我解決問題的最終代碼,即使它不太優雅。
public static String format(double value, int totalDigits)
{
String s = String.valueOf(value);
int decimal = s.indexOf('.');
// there is no decimal part, so simply return the String
if (decimal == -1)
{
return s;
}
else
{
int finalLength;
// example: 23.34324
// the final result will be length totalDigits + 1 because we will include the decimal
if (decimal < totalDigits)
{
finalLength = totalDigits + 1;
}
// example: 99999
// the final result will be length totalDigits because there will be no decimal
else if (decimal == totalDigits)
{
finalLength = totalDigits;
}
// example: 999999.999
// we can't make the final length totalDigits because the integer portion is too large
else
{
finalLength = decimal;
}
finalLength = Math.min(s.length(), finalLength);
return s.substring(0, finalLength);
}
}
public static void main(String[] args)
{
double[] data = { 1, 100, 1000, 10000, 100000, 99999, 99999.99, 9999.99, 999.99, 23.34324, 0.111111 };
for (double d : data)
{
System.out.printf("Input: %10s \tOutput: %10s\n", Double.toString(d), format(d, 5));
}
}
我會說你截斷/切斷數字,而不是四捨五入。 – 2012-04-02 15:10:21
是的,trucating數字會很好。 eee下面的答案非常接近,但'BigDecimal'在999.99的值處出現了一些奇怪的情況:將它舍入到了'999.98' – ulmangt 2012-04-02 15:19:14
這是浮點數和雙精度數的精度有限造成的僞像。更高的精度,你會看到999.98999這是精確的,你可以用浮動。但是如果你砍掉最後3個9,你將以999.98結束。 – 2012-04-02 15:28:26