Drop trailing digits of a floating point number

限于喜欢 提交于 2019-12-11 18:15:33

问题


I have some float variables in my java program:

float var1=1.23456f;
float var2=2.34567f;

In my calculations, the number of digits after decimal point in my float variable increases and decreases to maintain precision. for e.g. after some calculations System.out.println(var1); may print:

6.35

or

9.4500082E

or

88.25214

I want to round off these values to 3 decimal places and drop the subsequent decimal digits so that float gets rounded off like:

6.350   9.450   88.252

As far as i know, The NumberFormat and String.format() return the output as formatted String. How can i get the output as rounded off float to use it further in my calculations? Can i apply a rule to my float(Float) variables(Instance) to always round-off/drop the trailing digits after 3 decimal places?


回答1:


No, you can't get a "rounded off float." A float doesn't store a decimal number. Use BigDecimal if you want to do calculations using a specific number of decimal digits.

None of the other answers will get you what you actually want.




回答2:


One (not very efficient) way to do it is to still use the NumberFormat class to return the String (with 3 digits) and then use Float.parseFloat() to turn it back into a float.




回答3:


Use a simple helper method to round on arbitrary position:

 public static void main(String[] args) throws IOException {
    float fl = 1.2345f;
    System.out.println(round(fl, 3));
}

public static float round(float source, int positions) {
    long multiplier = (long) Math.pow(10, positions);
    return return ((float)((int) (source * multiplier)) / multiplier);
}

Please be aware, that thi snippet only demonstrates the idea and is limited to ~ 18 positions due to long overflow.



来源:https://stackoverflow.com/questions/18936350/drop-trailing-digits-of-a-floating-point-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!