Friday 24 May 2019

Java: Show only n digits after decimal point


Approach 1: Using DecimalFormat.format class
For example, below statements print 2 digits after the decimal point.
DecimalFormat decimalFormat = new DecimalFormat(".##");
double d1 = 1234567 / 123.0;
String formattedNumber = decimalFormat.format(d1);

App.java
package com.sample.app;

import java.io.IOException;
import java.text.DecimalFormat;

public class App {

 public static void main(String args[]) throws IOException {
  DecimalFormat decimalFormat = new DecimalFormat(".##");
  double d1 = 1234567 / 123.0;

  String formattedNumber = decimalFormat.format(d1);
  System.out.println("formattedNumber : " + formattedNumber);
  System.out.println("Actual Number : " + d1);

 }
}

Output
formattedNumber : 10037.13
Actual Number : 10037.130081300813

Approach 2: Using String.format
Below statements print 2 digits after the decimal point.

double d1 = 1234567 / 123.0;
String formattedNumber = String.format("%.2f", d1);


App.java
package com.sample.app;

import java.io.IOException;

public class App {

 public static void main(String args[]) throws IOException {

  double d1 = 1234567 / 123.0;
  String formattedNumber = String.format("%.2f", d1);
  
  System.out.println("formattedNumber : " + formattedNumber);
  System.out.println("Actual Number : " + d1);

 }
}

Output
formattedNumber : 10037.13
Actual Number : 10037.130081300813

You may like

No comments:

Post a Comment