In this post we will discuss about one of the basic java interview question and question is that How would you round a double value to certain decimal Precision and Scale ?
First of all let us understand what’s the difference between Precision and Scale.
Precision represent total number of digits (or significant digits) of a real number and Scale specifies number of digits after decimal place
For example, 91.763 has precision of 5 and scale of 3
No body wants to loose the precision value of the number as it will change the value by large amount. If you still willing to loose the precision simply you can divide the number by 10 to the power precision.
There are several ways in Java to round the double value to certain scale, as shown in the below example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package com.kkjavatutorials.util; import java.math.BigDecimal; import java.text.DecimalFormat; import java.math.RoundingMode; /** * @author KK JavaTutorials * Java Program to round a double value to certain decimal Precision and Scale */ public class RoundDoubleUtil { public static double round1(double amount, int scale) { BigDecimal bigDecimal = new BigDecimal(amount).setScale(scale,RoundingMode.HALF_EVEN); return bigDecimal.doubleValue(); } public static double round2(double amount) { return Math.round(amount * 100) / 100.0d; } public static double round3(double amount) { DecimalFormat decimalFormat = new DecimalFormat("#.00"); return Double.parseDouble(decimalFormat.format(amount)); } } |
Client program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.kkjavatutorials.client; import com.kkjavatutorials.util.RoundDoubleUtil; /** * KK JavaTutorials * Rounding a double value to certain decimal Precision and Scale */ public class RoundDoubleTest { public static void main(String[] args) { double amount = 8754.328354d; System.out.println(RoundDoubleUtil.round1(amount, 2)); System.out.println(RoundDoubleUtil.round2(amount)); System.out.println(RoundDoubleUtil.round3(amount)); } } |
Output:
8754.33
8754.33
8754.33
You may also like:
Why Java is not 100% Object-oriented language?
What are the differences between 32-bit and 64-bit versions of Java?
Can we call static method with null object?
Can we override static method in Java?
What will be the output of following java program?
What is the difference Between java.util.Date and java.sql.Date in Java ?
What is difference between using Serializable & Externalizable Interfaces in Java?
That’s all about How would you round a double value to certain decimal Precision and Scale ?
If you have any feedback or suggestion please feel free to drop in blow comment box.