Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving from Groovy to Java

In my grails project I'm moving all calculations to java classes.

Here is the link to source code (i've saved it in Google Docs).

Main purpose is to format current time into 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 if 'num' ends with 'part'. Examples:

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

P.S. num - is standard long (java.lang.Long) value and part - is greater than 0 and less or equals than 9 (1..9).

But this code works fine only in groovy classes.

In java class i got those results:

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

As i can see from gant log - all code are compiled by groovyc.

P.S.2 I'l compile this code with groovyc and javac to compare results. Because if i haven't make any mistake it could be a bug in groovyc. But this is my mistake i hope :)

like image 990
Oleksandr Avatar asked Dec 03 '22 12:12

Oleksandr


1 Answers

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

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

? If it needs to work for negative numbers you'll need to take the absolute value before the mod, but otherwise that should be fine.

like image 125
Jon Skeet Avatar answered Dec 24 '22 20:12

Jon Skeet