Java makes a double keep two decimal places
- 2020-04-01 02:51:51
- OfStack
mport java.text.DecimalFormat;
DecimalFormat df = new DecimalFormat("######0.00");
double d1 = 3.23456
double d2 = 0.0;
double d3 = 2.0;
df.format(d1);
df.format(d2);
df.format(d3);
The three results are:
3.23
0.00
2.00
Java reserved two decimal problem:
A:
Rounding
double f = 111231.5585;
BigDecimal b = new BigDecimal(f);
double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
Keep two decimal places
Method 2:
java.text.DecimalFormat df =new java.text.DecimalFormat("#.00");
df.format( The number you want to format );
Ex. :
new java.text.DecimalFormat("#.00").format(3.1415926)
#.00 means two decimal places #.0000 four decimal places and so on...
Three:
double d = 3.1415926;
String result = String .format("%.2f");
%.2f %. Represents any number before the decimal point & PI; The result of two decimal places is f for floating point
Method 4:
NumberFormat ddf1=NumberFormat.getNumberInstance() ;
void setMaximumFractionDigits(int digits)
The digits show the digits
Sets the maximum number of places to display after the decimal point for the formatting object, and the last place to display is rounded
import java.text.* ;
import java.math.* ;
class TT
{
public static void main(String args[])
{ double x=23.5455;
NumberFormat ddf1=NumberFormat.getNumberInstance() ;
ddf1.setMaximumFractionDigits(2);
String s= ddf1.format(x) ;
System.out.print(s);
}
}
import java.text.*;
DecimalFormat df=new DecimalFormat(".##");
double d=1252.2563;
String st=df.format(d);
System.out.println(st);