Skip to content

Instantly share code, notes, and snippets.

@antonijn
Last active August 29, 2015 13:57
Show Gist options
  • Select an option

  • Save antonijn/9585776 to your computer and use it in GitHub Desktop.

Select an option

Save antonijn/9585776 to your computer and use it in GitHub Desktop.
dtoa
private static String ltoa(long l, int bas) {
bool sign = l < 0;
if (sign) {
l = -l;
}
int digits;
int neg = 1;
for (digits = 0; l >= neg; ++digits) {
neg *= bas;
}
char[] chars = new char[digits + (sign ? 1 : 0)];
for (; digits > 0; --digits) {
byte b = l % bas;
l /= bas;
if (b >= bas) {
b = 'a' + b;
} else {
b = '0' + b;
}
chars[digits - (sign ? 0 : 1)] = b;
}
if (sign) {
chars[0] = '-';
}
return new String(chars);
}
private static String dtoa(double d, int base) {
long id = (long)d;
String b4c = ltoa(id, base);
d -= id;
while ((d - (long)d) != 0.0) {
d *= base;
}
id = (long)d;
String ac = ltoa(id, base);
return b4c + '.' + ac;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment