Record 1. Keep Decimal
Two-bit decimal, Java method, using NumberFormat to achieve, rounding results
Double Sourceprice = 4940.20;//Sourceprice = 1514940.20
double reductionprice = 0.1;
Double price = Sourceprice-reductionprice;
NumberFormat NF = numberformat.getnumberinstance ();
Notice here
nf.setmaximumfractiondigits (2);
System.out.println (Nf.format (price));
Output results:
(The result is one, in fact, the default is to remove the last 0.)
That is 4940.10, the final display 4940.1;
If the calculation result is 4940.00, then the final is 4940;
4,940.1
.
1,514,940.1 2. Separator
Note The separator, thousand separator, million separator, ...), which will display the separator directly, if you want to remove it, use
Nf.setgroupingused (FALSE);
The output turns into (no separator):
4940.1
.
1514940.1 3. Other ways to achieve
Double number = 12345.5593;//target value
SYSTEM.OUT.PRINTLN ("---calculation-keep 2 decimal-bigdecimal----------rounded--------------");
BigDecimal BigDecimal = new BigDecimal (number);
Double resnumber = Bigdecimal.setscale (2, bigdecimal.round_half_up). Doublevalue ();
System.out.println (Resnumber);
SYSTEM.OUT.PRINTLN ("---calculation-keep 2 decimal-decimalformat--------rounded----------------");
DecimalFormat DecimalFormat = new DecimalFormat ("#.00");
System.out.println (Decimalformat.format (number));
SYSTEM.OUT.PRINTLN ("---calculation-keep 2 decimal-string.format--------rounded----------------");
System.out.println (String.Format ("%.2f", number));
Output results:
12345.55