Search code examples
playn

In PlayN, is there a cross-platform method for formatting decimals?


How can I format a decimal value (e.g. 1.29854) so that it produces a string rounded to 2 decimal places (1.30)?

I'm lost because GWT doesn't support the native Java number formatting classes and I can't find any PlayN support for number formatting.

I've confirmed that, while the following works in the Java version, the HTML version fails to compile:

    DecimalFormat df = new DecimalFormat("0.00");
    String formattedValue = df.format(1.29854);

Solution

  • This mostly worked for my case (for one-digit numbers between 0 and 10):

            String formatted = ((Double) (Math.round(doubleValue * 100.0) / 100.0)).toString();
            formatted = (formatted + "00").substring(0,4);
    

    Verified in Java and HTML versions. Here's a unit test:

    @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);
        }
    }