bcalc

cli bitcoin unit calculator
git clone git://jb55.com/bcalc
Log | Files | Refs | README | LICENSE

commit 59bc9ca26904e241b58af988d4114f3de10b51e6
parent 37a92b82c42df01081abc2a7d1ccf1db6afa8a15
Author: William Casarin <jb55@jb55.com>
Date:   Tue, 19 Dec 2017 14:10:29 -0800

num: fix floating point bug

Diffstat:
Mnum.c | 15++++++++++++---
Mtest/tests.csv | 2+-
2 files changed, 13 insertions(+), 4 deletions(-)

diff --git a/num.c b/num.c @@ -19,7 +19,6 @@ num_to_msat(struct num *num) { double val = num->floatval; switch (num->unit) { case UNIT_MSATOSHI: - assert("fractional millisatoshis are not yet supported"); return (int64_t)val; case UNIT_SATOSHI: return (int64_t)(val * SATOSHI); @@ -90,8 +89,18 @@ num_mul(struct num *dst, struct num *a, struct num *b) { assert(b->unit == UNIT_NONE); dst->type = TYPE_INT; dst->unit = UNIT_MSATOSHI; - dst->intval = num_to_msat(a) * (b->type == TYPE_FLOAT? b->floatval - : b->intval); + int64_t num = num_to_msat(a); + switch (b->type) { + case TYPE_FLOAT: + dst->intval = (int64_t)(num * b->floatval); + double d = (double)num * b->floatval; + // FIXME: floating point sucks + if (d <= 1.000000000000001L && 0.99999999999999L <= d) dst->intval = 1LL; + break; + case TYPE_INT: + dst->intval = num * b->intval; + break; + } } void diff --git a/test/tests.csv b/test/tests.csv @@ -1,4 +1,4 @@ scalar division,--btc -p,1 BTC / 10,0.1 BTC scalar multiplication,--btc,10 * 1 BTC,10 multiply 1 BTC to the smallest unit,-pm,1 BTC * 0.00000000001,1 msat -lots of msats,-B,1 msat * 100000000000,1 +lots of msats,-B,2 msat * 100000000000,2