Migrating from Groovy to Java

In my grails project, I move all the calculations to Java classes.

Here is the link to the source code (I saved it in Google Docs).

The main goal is to format the current time in a string (in two languages). Examples:

1 day 2 hours 3 seconds 1  2  3  

But I have one method:

  private static boolean endsWith(final long num, final long part) { if (num / 10 < 1) { return num == part; } else { float val1 = (num - part) / 10; float val2 = (float) Math.floor(val1); return val1 == val2; } } 

It checks to see if 'num' ends with 'part'. Examples:

 assert endsWith(128, 1) == false assert endsWith(1, 1) == true assert endsWith(34, 4) == true 

PS num is the standard long (java.lang.Long) value, and part is greater than 0 and less than or equal to 9 (1..9).

But this code only works fine in groovy classes.

In the java class, I got the following results:

 endsWith(7, 7) == true endsWith(23, 3) == false endsWith(23, 1) == true 

As I can see from gant magazine - all code compiled by groovyc .

PS2 . I am compiling this code with groovyc and javac to compare the results. Because, if I'm not mistaken, it could be a groovyc mistake. But this is my mistake, I hope :)

+4
source share
3 answers

Why are you using floating point arithmetic? Why not just:

 private static boolean endsWith(final long num, final long part) { return (num % 10) == part; } 

? If it is necessary for negative numbers, you will need to accept an absolute value before the mod, but otherwise it should be fine.

+8
source

You should not compare floating point values ​​with == due to limited precision.

In fact, in this case, it doesn't seem like you need to go to a floating point operation at all. You can use % to get the remainder of the number and get the last few digits this way.

Here are a few examples (note the negative dividend sign)

 123 % 10 == 3 4567 % 100 == 67 -9876 % 10 == -6 

References

Related Questions


String alternative

Another option is that if performance is not very important, the easiest way is to simply convert to String and use String.endsWith . Thus, you also have no complications with negative numbers.

 System.out.println(String.valueOf(-9876).endsWith(String.valueOf(76))); // prints "true" 
+6
source

I'm not sure, but I do not like to convert your plugins ...

Could you just use return (num% 10) == part?

+3
source

Source: https://habr.com/ru/post/1316464/


All Articles