保留小數點後兩位(DecimalFormat)

private static void TestLogic()
{
	float n1 = 0.1f;
	float n2 = 123.126423f;
	float n3 = 0.123123f;
	float n4 = 1.1f;
	
	String tmp = "";				// 輸出
	tmp += "\r\n " + F2(n1);		// 0.100
	tmp += "\r\n " + F2(n2);		// 123.13
	tmp += "\r\n " + F2(n3);		// 0.123
	tmp += "\r\n " + F2(n4);		// 1.10
	
	System.out.print(tmp);
	Log.i("Tipper", tmp);
}

/** 將數值格式化 */
private static String F2(float num)
{
	DecimalFormat decimalFormat= new DecimalFormat("0.00");	
	if(num < 1) decimalFormat= new DecimalFormat("0.000");
	
    String Str=decimalFormat.format(num);
    
    return Str;
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章