mirror of
https://github.com/Qortal/altcoinj.git
synced 2025-02-14 19:25:51 +00:00
Better formatting in Utils.bitcoinValueToFriendlyString
This commit is contained in:
parent
f2a6e41c82
commit
0bdfa7b635
@ -294,15 +294,25 @@ public class Utils {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the given value in nanocoins as a 0.12 type string.
|
* Returns the given value in nanocoins as a 0.12 type string. More digits after the decimal place will be used
|
||||||
|
* if necessary, but two will always be present.
|
||||||
*/
|
*/
|
||||||
public static String bitcoinValueToFriendlyString(BigInteger value) {
|
public static String bitcoinValueToFriendlyString(BigInteger value) {
|
||||||
|
// TODO: This API is crap. This method should go away when we encapsulate money values.
|
||||||
boolean negative = value.compareTo(BigInteger.ZERO) < 0;
|
boolean negative = value.compareTo(BigInteger.ZERO) < 0;
|
||||||
if (negative)
|
if (negative)
|
||||||
value = value.negate();
|
value = value.negate();
|
||||||
BigInteger coins = value.divide(COIN);
|
BigDecimal bd = new BigDecimal(value, 8);
|
||||||
BigInteger cents = value.remainder(COIN);
|
String formatted = bd.toPlainString(); // Don't use scientific notation.
|
||||||
return String.format("%s%d.%02d", negative ? "-" : "", coins.intValue(), cents.intValue() / 1000000);
|
// Drop unnecessary zeros from the end.
|
||||||
|
int toDelete = 0;
|
||||||
|
for (int i = formatted.length() - 1; i > 1; i--) {
|
||||||
|
if (formatted.charAt(i) == '0')
|
||||||
|
toDelete++;
|
||||||
|
else
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return (negative ? "-" : "") + formatted.substring(0, formatted.length() - toDelete);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -51,6 +51,7 @@ public class UtilsTest {
|
|||||||
@Test
|
@Test
|
||||||
public void testFormatting() {
|
public void testFormatting() {
|
||||||
assertEquals("1.23", bitcoinValueToFriendlyString(toNanoCoins(1, 23)));
|
assertEquals("1.23", bitcoinValueToFriendlyString(toNanoCoins(1, 23)));
|
||||||
|
assertEquals("0.001", bitcoinValueToFriendlyString(BigInteger.valueOf(COIN.longValue() / 1000)));
|
||||||
assertEquals("-1.23", bitcoinValueToFriendlyString(toNanoCoins(1, 23).negate()));
|
assertEquals("-1.23", bitcoinValueToFriendlyString(toNanoCoins(1, 23).negate()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user