Java's float floating-point data retains two decimal places

Two methods have been used: DecimalFormat and Math.round().

usage:

1、DecimalFormat:(String java.text.NumberFormat.format(double number)方法)

float f = 0.5555f;

DecimalFormat df1 = new DecimalFormat(" #.00 "); //Reserve two decimal places, if it is a few tenths, the 0 before the decimal point will not be displayed, and the number of zeros after the decimal point will be reserved

df1.format(f);

#Indicates that if the bit is 0, it does not need to be displayed, and 0 means that if the bit is 0, it is still displayed;

The definition of the function is: ;

Therefore, the parameter passed is double, and float (implicit conversion) can also be passed, and the final result is String type.

2、Math.round():(int java.lang.Math.round(float a)方法)

float f = 1.222f;

f = Math.round(f * 100 ) / 100 f; //multiply by 100, then divide by 100 to convert to floating point type

/** Keep as many decimal places as you multiply

**Note that the Math.round() method passes the float type!

*/

Both methods round off.

If it is a floating-point type, it is recommended to use the Math.round method, or you can DIY code according to your needs.

 

For a detailed explanation, please see the code comments and console output: (including the format of decimalFloat and the implementation logic of the Math.round function)

package testMap;

import java.text.DecimalFormat;

public class TestFloat {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//四舍五入保留两位
		float f = 0.5555f;
		//decimalFormat是将double类型数据转换为字符串,并进行格式化
		//#表示这位如果是0则不必显示出来,0则表示这位如果是
		//format函数:String java.text.NumberFormat.format(double number)
		DecimalFormat df1 = new DecimalFormat("#.00");//首位0不显示出来,即0.1显示为  .1
		DecimalFormat df2 = new DecimalFormat("0.00");//首位0显示出来,即0.1显示为 0.1
		System.out.println("--------DecimalFormat----------");
		System.out.println("df1==" + df1.format(f));
		System.out.println("df2==" + df2.format(f));

		System.out.println(df1.format(f).getClass());//String类型
		System.out.println(Float.parseFloat(df1.format(f)));//转换为float类型
		System.out.println(String.valueOf(df1.format(f)));
//		System.out.println(Float.toString(df1.format(f)));//转换为String类型
		
		f = 0.595f;
		//Math.round()方法是将浮点类型数据 乘以10的多少次方 ,取整,然后 + 0.5 除以10的多少次方,取小数点后多少位
//		如乘以1000 则取小数点后3位
		System.out.println("---------Math.round()----------");
		System.out.println(Math.round(f * 100) / 100f);//四舍五入后如果末尾是0,自动省略,不显示
		
//		System.out.println(df1.format("1.2"));//参数必须是数值型String java.text.NumberFormat.format(double number)
		System.out.println(Float.toString(f));//转换为String输出效果
		System.out.println(Float.toString(f));//转换为String输出效果
		
		
		System.out.println("-----------Math.round()的正数非特殊值实现逻辑--------------");
		f = 11.115111f;
		int b = (int) (f * 100 + 0.5);
		float a = b / 100f;
		System.out.println("a==" + a);
		System.out.println((int)(f * 100 + 0.5) / 100f);
		
		f = -12.115f;
		System.out.println("负数" + Math.round(f * 100) / 100f);
		f = -12.116f;
		System.out.println("负数" + Math.round(f * 100) / 100f);
		
		
		System.out.println("-------Math.round()的负数非特殊值实现逻辑--------");
		int c = (int) (f * 100 - 0.5);
		float d = c / 100f;
		System.out.println("d==" + d);
		System.out.println((int)(d * 100 - 0.5) / 100f);
	}

}

Console output:

Screenshot below:

----The following is the console output-----(same as above, afraid of losing the picture)

--------DecimalFormat----------
df1==.56
df2==0.56
class java.lang.String
0.56
.56
---------Math.round( )----------
0.6
0.595
0.595
-----------Math.round() positive non-special value implementation logic ------------ --
a==11.12
11.12
Negative Number-12.11
Negative Number-12.12
-------Math.round()'s negative non-special value implementation logic --------
d==-12.12
-12.12

 

By the way, paste the code of NumberFormat.format():

/**
     * Specialization of format.
     *
     * @param number the double number to format
     * @return the formatted String
     * @exception        ArithmeticException if rounding is needed with rounding
     *                   mode being set to RoundingMode.UNNECESSARY
     * @see java.text.Format#format
     */
    public final String format(double number) {
        // Use fast-path for double result if that works
        String result = fastFormat(number);
        if (result != null)
            return result;

        return format(number, new StringBuffer(),
                      DontCareFieldPosition.INSTANCE).toString();
    }

 

Guess you like

Origin blog.csdn.net/Rhine_danji_ys/article/details/103853919