mathcontext保留2位小数_Java BigDecimal subtract()用法及代码示例

java.math.BigDecimal.subtract(BigDecimal val)用于计算两个BigDecimal的算术差。该方法用于查找大数的算术差异,而不会影响结果的精度。此方法对当前的BigDecimal执行操作,通过该操作调用此方法并将BigDecimal作为参数传递。

Java中有两种减法方法重载,如下所示:

subtract(BigDecimal val)

subtract(BigDecimal val, MathContext mc)

subtract(BigDecimal val)

用法:

public BigDecimal subtract(BigDecimal val)

参数:此方法接受参数val,该参数是要从此BigDecimal中减去的值。

返回值:此方法返回一个BigDecimal,该BigDecimal保留差异(this – val),其小数位数为max(this.scale(),val.scale())。

下面的程序用于说明BigDecimal的subtract()方法。

// Java program to demonstrate

// subtract() method of BigDecimal

import java.math.BigDecimal;

public class GFG {

public static void main(String[] args)

{

// BigDecimal object to store result

BigDecimal diff;

// For user input

// Use Scanner or BufferedReader

// Two objects of String created

// Holds the values to calculate the difference

String input1

= "545456468445645468464645";

String input2

= "425645648446468486486452";

// Convert the string input to BigDecimal

BigDecimal a

= new BigDecimal(input1);

BigDecimal b

= new BigDecimal(input2);

// Using subtract() method

diff = a.subtract(b);

// Display the result in BigDecimal

System.out.println("The difference of\n"

+ a + " \nand\n" + b + " "

+ "\nis\n" + diff + "\n");

}

}

输出:

The difference of

545456468445645468464645

and

425645648446468486486452

is

119810819999176981978193

subtract(BigDecimal val, MathContext mc)

用法:

public BigDecimal subtract(BigDecimal val, MathContext mc)

参数:此方法接受两个参数,一个是val,它是要从此BigDecimal中减去的值;一个是MathContext类型的mc。

返回值:此方法返回一个BigDecimal,该值保存差异(this – val),并根据上下文设置进行舍入。

下面的程序用于说明BigDecimal的subtract()方法。

// Java program to demonstrate

// subtract() method of BigDecimal

import java.math.*;

public class GFG {

public static void main(String[] args)

{

// BigDecimal object to store result

BigDecimal diff;

// For user input

// Use Scanner or BufferedReader

// Two objects of String created

// Holds the values to calculate the difference

String input1

= "468445645468464645";

String input2

= "4256456484464684864864";

// Convert the string input to BigDecimal

BigDecimal a

= new BigDecimal(input1);

BigDecimal b

= new BigDecimal(input2);

// Set precision to 10

MathContext mc

= new MathContext(10);

// Using subtract() method

diff = a.subtract(b, mc);

// Display the result in BigDecimal

System.out.println("The difference of\n"

+ a + " \nand\n" + b + " "

+ "\nis\n" + diff + "\n");

}

}

输出:

The difference of

468445645468464645

and

4256456484464684864864

is

-4.255988039E+21

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值