How do you crop BigDecimal results?

BigDecimal numerator = new BigDecimal(numerator);
BigDecimal denominator = new BigDecimal(denominator);
double result = numerator.divide(denominator).doubleValue();

Division on certain conditions leads to zero at the end (e.g. 0.0060). Separation of equal numbers leads to zero at the end (e.g 1.0).

I would prefer to trim the trailing zero in both cases. How should I do it?

+3
source share
3 answers

How to save the result as BigDecimal, and then you can set the scale on it only to display the significant digits you want.

BigDecimal # stripTrailingZeros(). , , , . 600.0 6E + 2. , , BigDecimal # setScale(), .

, /, .

, , . /.

double, , . , , , /, . , .

regex.

+3

, DecimalFormat. - :

DecimalFormat df = new DecimalFormat(".0");
double formatResult = df.format(result);

- 1.0, 1.278494890. , .

+1

, :

BigDecimal numerator = new BigDecimal(numerator);
BigDecimal denominator = new BigDecimal(denominator);
double result = numerator.divide(denominator).doubleValue();

. double, , .

, n , , .

.

BigDecimal numerator = new BigDecimal(numerator);
BigDecimal denominator = new BigDecimal(denominator);
BigDecimal div = numerator.divide(denominator);

BigDecimal, . 10 , System.out.println(div) 1.

, , numerator denominator

java.lang.ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result."

, double .

System.out.println(2312 / 2.543); //909.1624066063704
System.out.println(1.0 / 1.0);    //1.0
System.out.println(1 / 1);        //1

When using double numbers you can get 0at the end, for example 0.0060in your case. If you want to make sure what you get, you will have to convert your result to Stringusing

String dec = String.valueOf(10.0/10.0); //1.0

and then using

String newDec = dec.endsWith("0") ? dec.substring(0, dec.length() - 1) : dec;

to root out the last 0. Of course, if your line ends with .0, you have a choice based on your preference, whether you want to leave this leader .or not.

+1
source

Source: https://habr.com/ru/post/1775947/


All Articles