Java BigDecimal plus()方法

Java BigDecimal plus()方法

  1. java.math.BigDecimal.plus() 是java中的一个内置方法,用于返回一个BigDecimal,其值为(+this),其比例为this.scale()。这个方法只是简单地返回这个BigDecimal,与单数减法的negate()方法对称。

语法:

public BigDecimal plus()
Java

参数: 该函数不接受任何参数。

返回值: 该方法返回对象值,即this。

以下程序说明了上述方法的工作:

程序1:

// Java program to demonstrate the
// plus() method
 
import java.math.*;
 
public class Gfg {
 
    public static void main(String[] args)
    {
 
        // Assign value to b1
        BigDecimal b1 = new BigDecimal("-45.652");
 
        // Assign the result of plus method on
        // BigDecimal Objects b1 to b2
        BigDecimal b2 = b1.plus();
 
        // Print the value of b2
        System.out.println("The value of the BigDecimal is " + b2);
    }
}
Java
  1. 输出
The value of the BigDecimal is -45.652
Java

程序2:

// Java program to demonstrate the
// plus() method
 
import java.math.*;
 
public class gfg {
 
    public static void main(String[] args)
    {
 
        // Assign value to b1
        BigDecimal b1 = new BigDecimal("7458.3256");
 
        // Assign the result of plus method on
        // BigDecimal Objects b1 to b2
        BigDecimal b2 = b1.plus();
 
        // Print the value of b2
        System.out.println("The value of the BigDecimal is " + b2);
    }
}
Java
  1. 输出
The value of the BigDecimal is 7458.3256
Java
  1. java.math.BigDecimal.plus(MathContext mc) 是java中的一个内置方法,用于返回一个BigDecimal,其值为(+this),并根据上下文设置进行四舍五入。

语法:

public BigDecimal plus( _MathContext mc_ )
Java

参数: 该方法接受一个参数 mc ,它指的是要使用的四舍五入的背景,即数值将被四舍五入到哪一位。
返回值: 该方法返回BigDecimal对象的数值,并根据需要进行四舍五入。一个零的结果将有一个0的刻度。
下面的程序说明了上述方法的工作:

程序1:

// Java program to demonstrate the
// plus() method
 
import java.math.*;
 
public class gfg {
 
    public static void main(String[] args)
    {
 
        BigDecimal b1 = new BigDecimal("-452.325");
 
        MathContext m = new MathContext(4); // 4 precision
 
        // Perform plus on BigDecimal Objects b1 using m
        BigDecimal b2 = b1.plus(m);
 
        // Print the value of b2
        System.out.println("Result of plus is " + b2);
    }
}
Java

输出

Result of plus is -452.3
Java

程序2:

// Java program to demonstrate the
// plus() method
 
import java.math.*;
 
public class gfg {
 
    public static void main(String[] args)
    {
 
        BigDecimal b1 = new BigDecimal("-10.325");
 
        // 4 precision
        MathContext m = new MathContext(4);
 
        // Perform plus on BigDecimal Objects b1 using m
        BigDecimal b2 = b1.plus(m);
 
        // Print the value of b2
        System.out.println("Result of plus is " + b2);
    }
}
Java

输出

Result of plus is -10.33
Java

参考资料: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#plus()

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册