mirror of
https://github.com/Qortal/altcoinj.git
synced 2025-01-30 23:02:15 +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) {
|
||||
// TODO: This API is crap. This method should go away when we encapsulate money values.
|
||||
boolean negative = value.compareTo(BigInteger.ZERO) < 0;
|
||||
if (negative)
|
||||
value = value.negate();
|
||||
BigInteger coins = value.divide(COIN);
|
||||
BigInteger cents = value.remainder(COIN);
|
||||
return String.format("%s%d.%02d", negative ? "-" : "", coins.intValue(), cents.intValue() / 1000000);
|
||||
BigDecimal bd = new BigDecimal(value, 8);
|
||||
String formatted = bd.toPlainString(); // Don't use scientific notation.
|
||||
// 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
|
||||
public void testFormatting() {
|
||||
assertEquals("1.23", bitcoinValueToFriendlyString(toNanoCoins(1, 23)));
|
||||
assertEquals("0.001", bitcoinValueToFriendlyString(BigInteger.valueOf(COIN.longValue() / 1000)));
|
||||
assertEquals("-1.23", bitcoinValueToFriendlyString(toNanoCoins(1, 23).negate()));
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user