Java四捨五入2桁の小数点を保持する方法
3877 ワード
@Test
public void testRounding() {
// , double , 0
// :
double a = 3.1516;
BigDecimal aDouble = new BigDecimal(a);//aDouble : 3.1516000000000001790567694115452468395233154296875
//setScale()
double aResult = aDouble.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(aResult); //3.15
// :Math.round() , , 1 ,
double bResult = Math.round(5.2654555 * 100) * 0.01d;
System.out.println(bResult); //5.2700000000000005
// :
String cResult = new DecimalFormat("#.00").format(3.5);
System.out.println(cResult);//3.50
// :
String dResult = String.format("%.2f", 3.5);
System.out.println(dResult); //3.50
// %.2f %. 2 f
// : DecimalFormat NumberFormat
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
System.out.println(nf.format(Double.parseDouble("3.126")));
}
BigDecimalクラスのテスト
@Test
public void testBigDecimal() {
/************************** *********************************/
// double
BigDecimal aDouble = new BigDecimal(1.20);
System.out.println(aDouble);//1.1999999999999999555910790149937383830547332763671875
//String . String
BigDecimal aString = new BigDecimal("1.20");
System.out.println(aString);//1.20
BigDecimal aDouble2 = new BigDecimal(Double.toString(1.20));
System.out.println(aDouble2);//1.2
/****************************** ***********************************/
BigDecimal a = new BigDecimal("1.22");
System.out.println("construct with a String value: " + a);//1.22
BigDecimal b = new BigDecimal("2.22");
a.add(b);
System.out.println("aplus b is : " + a);//1.22
//BigDecimal (immutable) , , ,
// 。
a = a.add(b);
System.out.println("aplus2 b is : " + a);//3.44
/*********************************BigDecimal.setScale() *************************************/
/* BigDecimal.setScale()
setScale(1) ,
setScale(1,BigDecimal.ROUND_DOWN) , 2.35 2.3
setScale(1,BigDecimal.ROUND_UP) ,2.35 2.4
setScale(1,BigDecimal.ROUND_HALF_UP) ,2.35 2.4
setScale(1,BigDecimal.ROUND_HALF_DOWN) ,2.35 2.3, 5 */
BigDecimal bigDecimal = new BigDecimal("123.456");
//
System.out.println(bigDecimal.scale()); //3
}
DecimalFormatクラスのテスト
/**
* DecimalFormat NumberFormat , 。
* DecimalFormat
* :
* 0
* # , 0
* .
* ,
* ; 。
* - 。
* % 100
* ? 1000 ; ; , 。
* , 。
* X , 。
*/
@Test
public void testDecimalFormat() {
DecimalFormat df1 = new DecimalFormat("0.0");
DecimalFormat df2 = new DecimalFormat("#.#");
DecimalFormat df3 = new DecimalFormat("000.000");
DecimalFormat df4 = new DecimalFormat("###.###");
System.out.println(df1.format(12.34)); //12.3
System.out.println(df2.format(12.34)); //12.3
System.out.println(df3.format(12.34)); //0.12.340
System.out.println(df4.format(12.34)); //12.34
}