Friday, 27 March 2020

How to print double value without scientific notation?

There are multiple ways to print a double without scientific notation.

Approach1: Using System.out.ptintf.
System.out.printf("d: %f\n", d);

Approach 2: Using DecimalFormat.
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(6);
System.out.println("d : " + df.format(d));

Approach 3: Using BigDecimal.
String value1 = new BigDecimal(d).toPlainString();
System.out.println("d : " + value1);

Approach 4: Using String.format.
String value2 = String.format("%.8f", d);
System.out.println("d : " + value2);

Approach 5: Using java.util.Formatter.
String value3 = new Formatter().format("%.8f", d).toString();
System.out.println("d : " + value3);

Find the below working application.

App.java
package com.sample.app;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Formatter;

public class App {

 public static void main(String args[]) {
  double d = 123456789.1234;

  System.out.printf("d: %f\n", d);

  DecimalFormat df = new DecimalFormat("#");
  df.setMaximumFractionDigits(6);
  System.out.println("d : " + df.format(d));
  
  String value1 = new BigDecimal(d).toPlainString();
  System.out.println("d : " + value1);
  
  String value2 = String.format("%.8f", d);
  System.out.println("d : " + value2);
  
  Formatter formatter = new Formatter();
  String value3 = formatter.format("%.8f", d).toString();
  System.out.println("d : " + value3);
  
  formatter.close();
  
  
 }

}

Output

d: 123456789.123400
d : 123456789.1234
d : 123456789.1234000027179718017578125
d : 123456789.12340000
d : 123456789.12340000


You may like

No comments:

Post a Comment