Prevent exponential notation (E) from appearing when toString of Java Big Decimal

environment

Java 8 SpringBoot 1.5.10 Jackson Core 2.8.10

phenomenon

If you call toString while using the BigDecimal type, exponential notation (E) may appear. When I tried it in my environment, it started from 0.1 and remained as it was from 0.1 to 0.000001 (10 minus 6), but from 0.0000001 (10 minus 7), exponential notation (E) appeared.

BigDecimal fieldA = new BigDecimal("0.000001"); // .toString()Then 0.000001
BigDecimal fieldB = new BigDecimal("0.0000001"); // .toString()Then 1E-7

For the criteria for the appearance of exponential notation (E), see Document of BigDecimal.toString For details, please refer to that.

Correspondence

If you use toPlainString instead of toString, it will spit out as it is.

BigDecimal fieldA = new BigDecimal("0.0000001"); 
System.out.println(fieldA.toString()); // -> 1E-7
System.out.println(fieldA.toPlainString()); // -> 0.0000001

I want toPlainString when using Jackson

If you are using Jackson to convert Java objects to JSON, the default behavior is toString, so some numbers will have exponential notation (E). To prevent this, internally call toPlainString instead of toString WRITE_BIGDECIMAL_AS_PLAIN setting There is .0 / com / fasterxml / jackson / core / JsonGenerator.Feature.html # WRITE_BIGDECIMAL_AS_PLAIN). (From Jackson 2.3)

In case of Spring Boot, it is ok if you write the following settings in ʻapplication.yml`.

spring:
  jackson:
    generator:
      write_bigdecimal_as_plain: true

Digression

Note that if you use jq, it will be converted to a format that uses exponents. When I checked the operation, I curled it from the terminal, formatted it with jq, and checked it, so I was a little addicted to it.

#e appears when using jq
$ curl localhost:8081 | jq
{
  "fieldA": 1e-53,
  "fieldB": 9e-15
}

#e does not appear unless jq is used
$ curl localhost:8081     
{"fieldA":0.000001,"fieldB":0.0000001}

Recommended Posts

Prevent exponential notation (E) from appearing when toString of Java Big Decimal
[Java] Tips and error issues when converting from double to Big Decimal
Java Big Decimal
[Java] Use Big Decimal properly ~ 2018 ~