Skip to content

Instantly share code, notes, and snippets.

@mvberg
Created January 23, 2014 15:25
Show Gist options
  • Save mvberg/8580426 to your computer and use it in GitHub Desktop.
Save mvberg/8580426 to your computer and use it in GitHub Desktop.
price text
public static String priceText(Price price, Fraction frac) {
if (price == null) {
return NO_DATA;
}
long mantissa = price.mantissa();
int exponent = price.exponent();
boolean isMinus;
if (mantissa < 0) {
mantissa = -mantissa;
isMinus = true;
} else {
isMinus = false;
}
final long scale = frac.exponent();
while (exponent > scale) {
mantissa *= 10;
exponent--;
}
while (exponent < scale) {
mantissa /= 10;
exponent++;
}
long whole = frac.priceWhole(mantissa, exponent);
final char separator;
if (frac.base() == 10) {
mantissa %= frac.denominator();
separator = ASCII.DOT;
} else {
mantissa %= frac.decimalDenominator();
mantissa *= frac.denominator();
mantissa /= frac.decimalDenominator();
separator = ASCII.DASH;
}
long part = mantissa;
final int size = 64;
final char[] array = new char[size];
int index = size - 1;
long places = frac.places();
if (frac.base() == 10) {
places--;
}
/* part */if (places > 0) {
for (int k = 0; k < places; k++) {
final char alpha = (char) (part % 10 + ASCII._0_);
array[index--] = alpha;
part /= 10;
}
array[index--] = separator;
}
/* whole */if (whole == 0) {
array[index--] = ASCII._0_;
} else {
while (whole != 0) {
final char alpha = (char) (whole % 10 + ASCII._0_);
array[index--] = alpha;
whole /= 10;
}
if (isMinus) {
array[index--] = ASCII.MINUS;
}
}
final int offset = index + 1;
final int length = size - offset;
return new String(array, offset, length);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment