X Tutup
Skip to content

JSONObject: difference between getBigDecimal and optBigDecimal #438

@urfuchs

Description

@urfuchs

There is a difference between getBigDecimal and optBigDecimal.

JSONObject json = new JSONObject("{ \"key\" : 72.35 }");
BigDecimal bd1 = json.getBigDecimal(„key“);
BigDecimal bd2 = json.optBigDecimal(„key“, null);
System.out.println(bd1);
System.out.println(bd2);

prints:

72.35
72.349999999999994315658113919198513031005859375

Why is there a difference?

getBigDecimal converts the double to a String and than to a BigDecimal:
new BigDecimal(Double.valueOf(72.35).toString())
optBigDecimal converts the double directly to BigDecimal: new BigDecimal(Double.valueOf(72.35))

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      X Tutup