Skip to content

Instantly share code, notes, and snippets.

@bdkosher
Created February 29, 2016 02:07
Show Gist options
  • Select an option

  • Save bdkosher/574c9cdb4005ea47f050 to your computer and use it in GitHub Desktop.

Select an option

Save bdkosher/574c9cdb4005ea47f050 to your computer and use it in GitHub Desktop.
Freemarker millisecond truncation code extracted out and turned into a Groovy script to verify it's correctness
import groovy.transform.Field
@Field def _ = [do: { body ->
[while: { condition ->
body()
if (condition()) call(condition)
}]
}]
String formatMillis(int x, int forcedDigits = 3, int dstIdx = 0) {
if (x > 999 || x < 0) {
// Shouldn't ever happen...
throw new RuntimeException(
"Calendar.MILLISECOND > 999");
}
String res = ''
_.do {
res += String.valueOf ((48 + (x / 100)) as char);
forcedDigits--;
x = x % 100 * 10;
}.while { x != 0 || forcedDigits > 0 }
res
}
String formatMillis2(int x, int forcedDigits = 6, int dstIdx = 0) {
String res = ''
for (int i = forcedDigits - 1; i >= 0; --i) {
int power = Math.pow(10, i)
int place = x / power;
res += String.valueOf((48 + place) as char);
x = x - (place * power)
}
res
}
(8000..9000).each {
println "$it --> ${formatMillis2(it)}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment