How to get the decimal part of a float?

前端 未结 10 783
清酒与你
清酒与你 2020-11-28 10:43

I need to extract the decimal part of a float number, but I get weird results:

float n = 22.65f;
// I want x = 0.65f, but...

x = n % 1; // x = 0.6499996

x          


        
10条回答
  •  春和景丽
    2020-11-28 11:07

    If you just want to print the number to 2dp you can use DecimalFormat.

    DecimalFormat df= new DecimalFormat("#.##");
    System.out.println(df.format(f));
    

    If you want fixed point numbers internally use BigDecimal

提交回复
热议问题