Java: Convert Exponential form to Decimal number format in Java

While working with Doubles and Long numbers in Java you will see that most of the value are displayed in Exponential form. For example : In following we are multiplying 2.35 with 10000 and the result is printed.
//Division example Double a = 2.85d / 10000; System.out.println("1) " + a.doubleValue()); //Multiplication example a = 2.85d * 100000000; System.out.println("2) " + a.doubleValue());
Code language: Java (java)
Result:
1)  2.85E-4
2)  2.85E8
Thus you can see the result is printed in exponential format. Now you may want to display the result in pure decimal format like: 0.000285 or 285000000. You can do this simply by using class java.math.BigDecimal. In following example we are using BigDecimal.valueOf() to convert the Double value to BigDecimal and than .toPlainString() to convert it into plain decimal string.
import java.math.BigDecimal; //.. //.. //Division example Double a = 2.85d / 10000; System.out.println("1) " + BigDecimal.valueOf(a).toPlainString()); //Multiplication example a = 2.85d * 100000000; System.out.println("2) " + BigDecimal.valueOf(a).toPlainString());
Code language: Java (java)
Result:
1)  0.000285
2)  285000000
The only disadvantage of the above method is that it generates lonnnnggg strings of number. You may want to restrict the value and round off the number to 5 or 6 decimal point. For this you can use java.text.DecimalFormat class. In following example we are rounding off the number to 4 decimal point and printing the output.
import java.text.DecimalFormat; //.. //.. Double a = 2.85d / 10000; DecimalFormat formatter = new DecimalFormat("0.0000"); System.out.println(formatter .format(a));
Code language: Java (java)
Result:
0.0003
Happy converting :)

View Comments

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

4 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

4 years ago