Convert BigDecimal to Int in Java - The best way to convert BigDecimal to Int

Overview

In this tutorial, we show you how to convert BigDecimal to int in Java. The snippet code below will show you how to convert java.math.BigDecimal to the primitive data type (int).

Convert BigDecimal to Int in Java

Using java.math.BigDecimal.intValue() method

In the following code shows how to use java.math.BigDecimal.intValue() method.
package com.jackrutorial;

import java.math.BigDecimal;

public class BigDecimalToIntExample1 {

 public static void main(String[] args) {
  BigDecimal bdNumber = new BigDecimal("2.8");
  System.out.println("The BigDecimal is : " + bdNumber);

  // Returns the value of this BigDecimal as an int.
  int intNumber = bdNumber.intValue();
  System.out.println("intNumber: " + intNumber);
 }
}

Output

The BigDecimal is : 2.8
intNumber: 2

Using java.math.BigDecimal().setScale(0, RoundingMode.DOWN).intValueExact() method

In the following code shows how to use java.math.BigDecimal.setScale(0, RoundingMode.DOWN).intValueExact() method.
package com.jackrutorial;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class BigDecimalToIntExample2 {

 public static void main(String[] args) {
  BigDecimal bdNumber = new BigDecimal("2.8");
  System.out.println("The BigDecimal is : " + bdNumber);

  // Java 7 or below
  int intNumber = bdNumber.setScale(0, RoundingMode.DOWN).intValueExact();
  System.out.println("intNumber: " + intNumber);
 }
}

Output

The BigDecimal is : 2.8
intNumber: 2

Using java.math.BigDecimal..toBigInteger().intValueExact()

In the following code shows how to use java.math.BigDecimal.toBigInteger().intValueExact() method for Java 8.
package com.jackrutorial;

import java.math.BigDecimal;

public class BigDecimalToIntExample3 {

 public static void main(String[] args) {
  BigDecimal bdNumber = new BigDecimal("2.8");
  System.out.println("The BigDecimal is : " + bdNumber);

  // java 8
  // Converts this BigDecimal to an int, checking for lost information.
  int intNumber = bdNumber.toBigInteger().intValueExact();
  System.out.println("intNumber: " + intNumber);
 }
}

Output

The BigDecimal is : 2.8
intNumber: 2
Previous Post
Next Post

post written by: