Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

java round double/float to 2 decimal places

In this post, we will see how to round Double to 2 decimal places in java.
There are many ways to do it.Let’s go through few ways.

  • Math.round(double*100.0)/100.0
  • DecimalFormat(“###.##”)

Let’s understand each with the help of simple example.

Math.round(double*100.0)/100.0

package org.arpit.java2blog;

public class MathRoundMain {

	public static void main(String[] args) {
		
		double d=2343.5476;
		double roundedDouble = Math.round(d * 100.0) / 100.0;
		System.out.println("Rounded double: "+roundedDouble);
		
		float f=2343.5476f;
		double roundedFloat = Math.round(d * 100.0) / 100.0;
		System.out.println("Rounded float: "+roundedFloat);
	}

}

Output:

You must be wondering how this works.

double*100.0 – 234354.76
Math.round(double*100.0) – 234355.00 (round to nearest value)
Math.round(double*100.0)/100.0 – 2343.55

DecimalFormat

You can use DecimalFormat too to round number to 2 decimal places.

package org.arpit.java2blog;

import java.text.DecimalFormat;

public class DecimalFormatMain {

	public static void main(String[] args) {
		double d=2343.5476;
		DecimalFormat df = new DecimalFormat("###.##");
		System.out.println("Rounded double (DecimalFormat) : " + df.format(d));
	}

}

Output:

Rounded double (DecimalFormat) : 2343.55

That’s all about rounding double/float to 2 decimal places

The post java round double/float to 2 decimal places appeared first on Java2Blog.



This post first appeared on How To Learn Java Programming, please read the originial post: here

Share the post

java round double/float to 2 decimal places

×

Subscribe to How To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×