這種情況多(0到10之間的一個位數)工作了我的情況:
String formatted = ((Double) (Math.round(doubleValue * 100.0)/100.0)).toString();
formatted = (formatted + "00").substring(0,4);
已通過Java和HTML版本驗證。這是一個單元測試:
@Test
public void testNumberFormatting() {
ArrayList<Double> testCases = Lists.newArrayList(
0.0, 0.986, 1.0, 1.2, 1.29, 1.295);
ArrayList<String> expectResults = Lists.newArrayList(
"0.00", "0.99", "1.00", "1.20", "1.29", "1.30");
for (int n=0; n<testCases.size(); n++) {
Double testCase = testCases.get(n);
String formatted = ((Double) (Math.round(testCase * 100.0)/100.0)).toString();
formatted = (formatted + "00").substring(0,4);
assertEquals(expectResults.get(n), formatted);
System.out.println(formatted);
}
}