How to round bigdecimal

 

java rounding

package Test;

import java.math.BigDecimal; //Introduce this package

public class Test {
public static void main(String[] args) {

double i = 3.856;

// Round off decimals
System.out.println(" Round off decimals: Math.floor(3.856)=" + (int) Math.floor(i));

// Rounding up
System.out.println("Rounding up and down: (3.856)="
+ new BigDecimal(i).setScale(0, BigDecimal.ROUND_HALF_UP));

// Rounding to two decimal places
System.out.println("Rounding to integer: (3.856)="
+ new BigDecimal(i).setScale(2, BigDecimal.ROUND_HALF_UP));

// Round up, take the upper limit
System.out.println("Round up: Math.ceil(3.856)=" + (int) Math.ceil(i));

// Round off decimals
System.out.println(" Round off decimals: Math.floor(-3.856)=" + (int) Math.floor(-i));
// Round off and round off
System.out .println("Round up: (-3.856)="
+ new BigDecimal(-i).setScale(0, BigDecimal.ROUND_HALF_UP));

// Rounding to two decimal places
System.out.println("Rounding to whole: (-3.856)="
+ new BigDecimal(-i).setScale(2, BigDecimal.ROUND_HALF_UP));

// Round up, take the upper limit
System.out.println("Round (-3.856)=" + (int) Math.ceil(-i));
}
}

 

// print the result

Round off decimals: Math.floor(3.856)=3
Round off: (3.856)=4
Round off: (3.856)=3.86 Round off
: Math.ceil(3.856) =4 Round off
decimals: Math .floor(-3.856)=-4
rounding: (-3.856)=-4 rounding: (-3.856)
=-3.86
rounding (-3.856)=-3 maolinquan

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326278252&siteId=291194637