简体   繁体   中英

How to get around a Possible Loss of Precision Error in java

I'm working on a scaling system, to scale numbers up 25% and round to the nearest integer, and to do this, I am trying to rely on the loss of precision by transferring a double into an int. Is there any way to get around this? or should I go about it in a different way?

public int[] scaleMarks(int[] marks)
{
    double scale = 1.25;
    double temp1;
    int temp2;

    for(int i = 0; i < marks.length; i++)
    {
        temp1 = marks[i] * scale;
        temp2 = marks[i] * scale; //***Loss of precision here***

        if(temp1-temp2>= 0.5)
        {
            temp2++;
        }
        marks[i] = temp2;

    }


    return marks;
}

您需要使用Math.round对产品进行舍入,以便可以安全地将其转换为int

marks[i] = (int) Math.round(marks[i] * scale);

If you want round-to-nearest, rather than truncation, you need to use Math.round.

public class Test {
  public static void main(String[] args) {
    System.out.println((int)0.999999);
    System.out.println(Math.round(0.999999));
  }
}

outputs

0
1

You can use Math.round function to avoid it:

(int)Math.round(marks[i] * scale);

EDIT: You will have to cast it to int because if you don't do that the result will be wrong (because scale it's a double ).

I expect it will be helpful for you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM