Java double round 2 digit

Содержание
  1. java round double/float to 2 decimal places
  2. Read also:
  3. 7 ways to format double to 2 decimal places in java
  4. 7 ways to format float to 2 decimal places in java
  5. Using BigDecimal
  6. Using Math.round(double*100.0)/100.0
  7. Using Apache common Math
  8. Was this post helpful?
  9. Share this
  10. Related Posts
  11. Author
  12. Related Posts
  13. PI in Java
  14. Calculate total surface area of Cylinder in java
  15. Calculate total surface area of Hemisphere in java
  16. Get random number between 0 and 1 in java
  17. How to get square root of number in java
  18. Power function in java
  19. Округлите число с плавающей точкой до 2 знаков после запятой в Java
  20. 1. Использование Math.round() метод
  21. 2. Использование DecimalFormat.format() метод
  22. Round a Double to Two Decimal Places in Java
  23. Round of a double to Two Decimal Places Using Math.round(double*100.0)/100.0
  24. Round of a double to Two Decimal Places Using BigDecimal
  25. Round of a double to Two Decimal Places Using DecimalFormat
  26. Round of a double to Two Decimal Places Using Apache Common Math
  27. Related Article — Java Double
  28. How to Round Float or Double in Java
  29. 1. Using BigDecimal
  30. BigDecimal – Round double to 2 decimal points example
  31. BigDecimal – Round float to 2 decimal points example
  32. 2. Using DecimalFormat
  33. Round to 2 decimal points
  34. Round to 1 decimal point
  35. Format Pattern “0.00” vs “#.##”
  36. Rounding Modes:
  37. Decimal Format – Round double to 2 decimal points example
  38. Decimal Format – Round float to 2 decimal points example
  39. 3. Using String.format(“%.2f”, floatValue)
  40. Related Posts:

java round double/float to 2 decimal places

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

Read also:

7 ways to format double to 2 decimal places in java

7 ways to format float to 2 decimal places in java

Using BigDecimal

You can convert double or float to BigDecimal and use setScale() method to round double/float to 2 decimal places.
Here is the example:

Читайте также:  Count dict items python

Using Math.round(double*100.0)/100.0

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

Using Apache common Math

You can also use Apache common ‘s math library to round double or float to 2 decimal places.
Add the following dependency to pom.xml .

You can find versions of commons-math over here.
Here is the example:

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

Was this post helpful?

Share this

Author

PI in Java

Table of ContentsPI Constant in JavaPI Constant in Java Math Class The Pi is a constant value in Mathematics that represents a floating-point value 3.1415. It is mostly used in geometry to calculate area, circumference, volume, etc. If you have studied geometry in your academic, then you may be aware of use of Pi such […]

Calculate total surface area of Cylinder in java

In this post, we will see how to calculate total surface area of Cylinder in java. Formula of calculating total surface area of Cylinder is: Surface area of Cylinder = 2 *Π * r * r + 2 *Π * r * h Where r is radius of cylinder and h is height of cylinder […]

Calculate total surface area of Hemisphere in java

In this post, we will see how to calculate total surface area of Hemisphere in java. Hemisphere is exactly half of sphere. There can be many practical examples of Hemisphere. You can divide earth into two hemisphere i.e. Northen Hemisphere and Southern Hemisphere. Formula of calculating total surface area of Hemisphere is: surface area of […]

Get random number between 0 and 1 in java

In this post, we will see how to get random number between 0 to 1 in java. We have already seen random number generator in java. We can simply use Math.random() method to get random number between 0 to 1. Math.random method returns double value between o(inclusive) to 1(exclusive). [crayon-64be624e20f05790230040/] When you run above program, […]

How to get square root of number in java

Table of ContentsSyntaxReturn typeSquare root of number In this tutorial. we will see if how to get square root of number in java. It is very simple to get square root of number in java. You can simply use Math’s sqrt() method to calculate square root of number. Syntax [crayon-64be624e22dd4369577045/] Return type It returns square […]

Power function in java

Table of ContentsSyntaxInternal working Power function in java is used to get first argument’s power to 2nd argument. For example: Let’s say you want to calculate 2 to the power 4. That will be 2*2*2*2=16 In java, you can do it by : Math.pow(2,4) =16 Syntax [crayon-64be624e21b79085652916/] Example : Let’s use power function in java. […]

Источник

Округлите число с плавающей точкой до 2 знаков после запятой в Java

В этом посте будет обсуждаться, как округлить двойное число до 2 знаков после запятой в Java.

1. Использование Math.round() метод

The Math.round() метод возвращает значение указанного двойного округления до ближайшего длинного значения. Следующее решение демонстрирует его использование для округления двойного числа до 2 знаков после запятой. Обратите внимание, что количество нулей указывает количество десятичных знаков.

Обратите внимание, что количество нулей указывает количество десятичных знаков. Поэтому, чтобы округлить до 3 знаков после запятой, выполните следующие действия:

Вот альтернативная, эквивалентная версия приведенного выше кода:

Арифметика с плавающей запятой может быть очень сложной, и этот метод также не всегда работает так, как хотелось бы. Например, значение 296.335 округляется до 296.33 вместо 296.34 .

2. Использование DecimalFormat.format() метод

Здесь идея состоит в том, чтобы создать DecimalFormat используя указанный шаблон и вызовите DecimalFormat.format() метод для получения отформатированной строки. Чтобы ограничить двойное значение двумя десятичными точками, вы можете использовать шаблон #.## . Вы также можете установить RoundingMode с использованием setRoundingMode() метод. Этот подход страдает той же проблемой, что и первый подход. т. е. значение 296.335 округляется до 296.33 вместо 296.34 .

Источник

Round a Double to Two Decimal Places in Java

Round a Double to Two Decimal Places in Java

  1. Round of a double to Two Decimal Places Using Math.round(double*100.0)/100.0
  2. Round of a double to Two Decimal Places Using BigDecimal
  3. Round of a double to Two Decimal Places Using DecimalFormat
  4. Round of a double to Two Decimal Places Using Apache Common Math

In the previous tutorial article, we have understood how to convert an Array to ArrayList in Java using various methods with detailed examples. We will look at more types of Java usage through different forms of scenario analysis.

In this tutorial article, we will discuss on rounding of a double to two decimal places using Java. There are four ways to round up a double value to two decimal places such as Math.round() , BigDecimal using the setScale() method, DecimalFormat and Apache Common library.

Let us discuss each way through examples.

Round of a double to Two Decimal Places Using Math.round(double*100.0)/100.0

The Math.round() method is used in Java to round a given number to its nearest integer. Since in this article, we will learn rounding of a double to 2 decimal places, the application of Math.round() will include (double*100.0)/100.0 .

Let us follow the below example.

import java.util.*; import java.lang.*; import java.io.*;  public class Main   public static void main(String[] args)    double d = 7435.9876;  double roundDbl = Math.round(d*100.0)/100.0;  System.out.println("Rounded Double value: "+roundDbl);  > > 
Rounded Double value: 7435.99 

Round of a double to Two Decimal Places Using BigDecimal

In this way, we can first convert double to BigDecimal and then use the setScale() method to round the converted BigDecimal to two decimal places. Let us understand the below example.

import java.util.*; import java.lang.*; import java.io.*; import java.math.BigDecimal; import java.math.RoundingMode;  public class Main   public static void main(String[] args)    double val1 = 4312.186462;  System.out.println("Double value: "+val1);   BigDecimal bd = new BigDecimal(val1).setScale(2, RoundingMode.HALF_UP);  double val2 = bd.doubleValue();  System.out.println("Rounded Double value: "+val2);  > > 
Double value: 4312.186462 Rounded Double value: 4312.19 

Round of a double to Two Decimal Places Using DecimalFormat

We can also round a double value to two decimal places using DecimalFormat . Let us discuss in the following example.

import java.util.*; import java.lang.*; import java.io.*; import java.text.DecimalFormat;  public class Main   public static void main(String[] args)    double val1 = 6482.236789;  System.out.println("Double value: "+val1);   DecimalFormat df = new DecimalFormat("###.##");  System.out.println("Rounded Double value (DecimalFormat): "+df.format(val1));  > > 
Double value: 6482.236789 Rounded Double value: 6482.24 

Round of a double to Two Decimal Places Using Apache Common Math

A special kind of math library in Java is used to round a double to two decimal places, which is Apache Common . Let us discuss its utilization in the following example.

We need to add this library dependency in an xml file within the Java project.

   org.apache.commons   commons-math3   3.6.1  

Now let’s check the apache library implementation for rounding a double to two decimal places.

import java.util.*; import java.lang.*; import java.io.*; import org.apache.commons.math3.util.Precision;  public class Main   public static void main(String[] args)    double input = 9476.2351;  double roundedDbl = Precision.round(input,2);  System.out.println("Rounded Double value: "+roundedDbl);  > > 
Rounded Double value: 9476.24 

It is recommended to follow the first three ways for simple Java applications.

Related Article — Java Double

Copyright © 2023. All right reserved

Источник

How to Round Float or Double in Java

In this tutorial, you will learn how to round a Float or a Double value to 2 decimal places in Java.

1. Using BigDecimal

One of the ways to round a float or a double value is to use BigDecimal class.

BigDecimal bigDecimalDouble = new BigDecimal(doubleValue);

BigDecimal class allows us to set a scale and a rounding mode.

bigDecimalDouble.setScale(2, RoundingMode.HALF_UP);
  • scale – is a number of decimal points,
  • RoundingMode.HALF_UP – is a rounding mode used. Other rounding modes are:
    • ROUND_UP,
    • ROUND_DOWN,
    • ROUND_CEILING,
    • ROUND_FLOOR,
    • ROUND_HALF_DOWN,
    • ROUND_HALF_EVEN,
    • ROUND_UNNECESSARY

    BigDecimal – Round double to 2 decimal points example

    import java.math.BigDecimal; import java.math.RoundingMode; public class RoundDouble < public static void main(String args[]) < double doubleValue = 11.8989; BigDecimal bigDecimalDouble = new BigDecimal(doubleValue); System.out.println(bigDecimalDouble); // Prints 11.8988999999999993661958797019906342029571533203125 BigDecimal bigDecimalWithScale = bigDecimalDouble.setScale(2, RoundingMode.HALF_UP); System.out.println(bigDecimalWithScale); // Prints 11.90 >>

    Similarly, you can use BigDecimal to round a float value to 2 decimal points.

    BigDecimal – Round float to 2 decimal points example

    import java.math.BigDecimal; import java.math.RoundingMode; public class RoundDouble < public static void main(String args[]) < float floatValue = 11.8989f; BigDecimal bigDecimalFloat = new BigDecimal(floatValue); System.out.println(bigDecimalFloat); // Prints 11.89890003204345703125 BigDecimal bigDecimalFloatWithScale = bigDecimalFloat.setScale(2, RoundingMode.HALF_UP); System.out.println(bigDecimalFloatWithScale); // Prints 11.90 >>

    2. Using DecimalFormat

    Another way to round a float or a double value to 2 decimal points is to use the DecimalFormat class. DecimalFormat class allows us to create an output pattern and then set a rounding mode that we want to apply to a value.

    Round to 2 decimal points

    DecimalFormat decimalFormat = new DecimalFormat("0.00"); decimalFormat.setRoundingMode(RoundingMode.HALF_UP);

    Round to 1 decimal point

    DecimalFormat decimalFormat = new DecimalFormat("0.0"); decimalFormat.setRoundingMode(RoundingMode.HALF_UP);

    Format Pattern “0.00” vs “#.##”

    Both of these formatting patterns work similarly, except that “#.##” will not display a digit if the last decimal point is zero. For example,

    if doubleValue = 11.90 then BigDecimal("#.##") will print 11.9

    On the other hand, the formatting pattern “0.00” will always display a digit even if it is zero. For example,

    if doubleValue = 11.90 then BigDecimal("0.00") will print 11.90

    Rounding Modes:

    • ROUND_UP,
    • ROUND_DOWN,
    • ROUND_CEILING,
    • ROUND_FLOOR,
    • ROUND_HALF_DOWN,
    • ROUND_HALF_EVEN,
    • ROUND_UNNECESSARY

    Let’s have a look at the complete example.

    Decimal Format – Round double to 2 decimal points example

    import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormat; public class RoundDouble < public static void main(String args[]) < double doubleValue = 11.8989; DecimalFormat decimalFormat = new DecimalFormat("0.00"); decimalFormat.setRoundingMode(RoundingMode.HALF_UP); System.out.println(decimalFormat.format(doubleValue)); //11.90 >>

    Decimal Format – Round float to 2 decimal points example

    import java.math.RoundingMode; import java.text.DecimalFormat; public class RoundFloat < public static void main(String args[]) < float floatValue = 11.8989f; DecimalFormat decimalFormat = new DecimalFormat("0.00"); decimalFormat.setRoundingMode(RoundingMode.HALF_UP); System.out.println(decimalFormat.format(floatValue)); //11.90 >>

    3. Using String.format(“%.2f”, floatValue)

    Alternatively, you can use String.format() function to format the input value to 2 decimal points. Although, String.format() does not allow to change the rounding mode. The only rounding mode applicable is half-up.

    I hope this tutorial was helpful for you.

    There are many other useful tutorials you can find on this site. To find Java-related tutorials, check out the Java tutorials page.

    Источник

Оцените статью