From 0bdfa7b6355505d8a5c4ccac41624df59251277c Mon Sep 17 00:00:00 2001 From: Mike Hearn Date: Wed, 9 Jan 2013 23:41:32 +0100 Subject: [PATCH] Better formatting in Utils.bitcoinValueToFriendlyString --- .../java/com/google/bitcoin/core/Utils.java | 18 ++++++++++++++---- .../com/google/bitcoin/core/UtilsTest.java | 1 + 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/core/src/main/java/com/google/bitcoin/core/Utils.java b/core/src/main/java/com/google/bitcoin/core/Utils.java index 6e295d62..36ce8444 100644 --- a/core/src/main/java/com/google/bitcoin/core/Utils.java +++ b/core/src/main/java/com/google/bitcoin/core/Utils.java @@ -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); } /** diff --git a/core/src/test/java/com/google/bitcoin/core/UtilsTest.java b/core/src/test/java/com/google/bitcoin/core/UtilsTest.java index c014ddcc..2517493c 100644 --- a/core/src/test/java/com/google/bitcoin/core/UtilsTest.java +++ b/core/src/test/java/com/google/bitcoin/core/UtilsTest.java @@ -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())); }