简体   繁体   English

在JAVA中,可以使用大十进制浮点数和双数减去

[英]In JAVA, can float and double number subtracted by using big decimal

Here is the Code(i am giving fraction of code) Below code is of withdraw of savings account:- 这是代码(我给出代码的一部分)下面的代码是储蓄帐户的提款:

I have declared variables as below:- 我声明了如下变量:

protected static double balance;
protected static float amount;

So i opened account with balance as 7095, then i am performing withdraw operation, entering amount as 100.0. 所以我开了一个余额为7095的帐户,然后我执行提款操作,输入金额为100.0。 I am getting below results which is wrong. 我得到的结果不对,这是错误的。 If i enter amount as 100, getting expecting results. 如果我输入金额为100,则会获得预期的结果。 Need help. 需要帮忙。

Total balance:- 7095
Withdraw amount:- 48
Current balance:- 7047

  BigDecimal amount3 = new BigDecimal(balance);
  BigDecimal amount4 = new BigDecimal(amount) ;
  System.out.println("Total balance" +amount3);
  System.out.println("Withdraw amount" + amount4);
  Object obj = new Object();
  obj = (amount3.subtract(amount4));
  System.out.println("Current balance" +obj);

Binary floating-point ( float and double in Java) can only represent fractional numbers of a form counter-intuitive to base-10-using humans. 二进制浮点数(在Java中为floatdouble )只能表示与使用base-10的人类相反的形式的分数。 The number 0.1 is famously not representable in binary floating-point, for instance. 例如,数字0.1在二进制浮点数中无法表示。

The problem with binary floating-point is not addition and subtraction. 二进制浮点的问题不是加法和减法。 The problem is the representation of (some) fractional numbers of interest to you, in particular, decimal numbers. 问题在于您感兴趣的(某些)小数的表示形式,特别是十进制数。 Therefore, it will not help to convert to BigDecimal numbers that are already represented in binary floating-point. 因此,将无助于转换为已经在二进制浮点数中表示的BigDecimal数。 They have already been approximated at the instant it was chosen to represent them as float and double . 在选择将它们表示为floatdouble已经对它们进行了近似。 Computing as accurately as you want won't erase the representation error that was made then. 尽可能精确地进行计算不会消除当时发生的表示错误

If you care about representing decimal numbers exactly, do not use binary floating-point to store them. 如果要精确表示十进制数,请不要使用二进制浮点数来存储它们。 In other words, do not declare amount and balance with binary floating-point types float and double . 换句话说,不要使用二进制浮点类型floatdouble声明amountbalance

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM