Java BigDecimal without E

匿名 (未验证) 提交于 2019-12-03 08:35:02

问题:

I have a BigDecimal variable

BigDecimal x = new BigDecimal("5521.0000000001"); 

Formula:

x = x.add(new BigDecimal("-1")       .multiply(x.divideToIntegralValue(new BigDecimal("1.0")))); 

I want to remove the integer part, to get the value x = ("0.0000000001"), but my new value is 1E-10 and not the 0.0000000001.

回答1:

To get a String representation of the BigDecimal without the exponent part, you can use
BigDecimal.toPlainString(). In your example:

BigDecimal x = new BigDecimal("5521.0000000001"); x = x.add(new BigDecimal("-1").               multiply(x.divideToIntegralValue(new BigDecimal("1.0")))); System.out.println(x.toPlainString()); 

prints

0.0000000001 


回答2:

Perhaps using BigDecimal isn't really helping you.

double d = 5521.0000000001; double f = d - (long) d; System.out.printf("%.10f%n", f); 

prints

0.0000000001 

but the value 5521.0000000001 is only an approximate representation.

The actual representation is

double d = 5521.0000000001; System.out.println(new BigDecimal(d)); BigDecimal db = new BigDecimal(d).subtract(new BigDecimal((long) d)); System.out.println(db); 

prints

5521.000000000100044417195022106170654296875 1.00044417195022106170654296875E-10 

I suspect whatever you are trying to is not meaningful as you appear to be trying to obtain a value which is not what you think it is.



回答3:

Try using BigDecimal.toPlainString() to get value as plain string as you require.



回答4:

If you want to do this at your BigDecimal object and not convert it into a String with a formatter you can do it on Java 8 with 2 steps:

  1. stripTrailingZeros()
  2. if scale < 0 setScale to 0 if don't like esponential/scientific notation

You can try this snippet to better understand the behaviour

BigDecimal bigDecimal = BigDecimal.valueOf(Double.parseDouble("50")); bigDecimal = bigDecimal.setScale(2); bigDecimal = bigDecimal.stripTrailingZeros(); if (bigDecimal.scale()<0) bigDecimal= bigDecimal.setScale(0); System.out.println(bigDecimal);//50 bigDecimal = BigDecimal.valueOf(Double.parseDouble("50.20")); bigDecimal = bigDecimal.setScale(2); bigDecimal = bigDecimal.stripTrailingZeros(); if (bigDecimal.scale()<0) bigDecimal= bigDecimal.setScale(0); System.out.println(bigDecimal);//50.2 bigDecimal = BigDecimal.valueOf(Double.parseDouble("50")); bigDecimal = bigDecimal.setScale(2); bigDecimal = bigDecimal.stripTrailingZeros(); System.out.println(bigDecimal);//5E+1 bigDecimal = BigDecimal.valueOf(Double.parseDouble("50.20")); bigDecimal = bigDecimal.setScale(2); bigDecimal = bigDecimal.stripTrailingZeros(); System.out.println(bigDecimal);//50.2 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!