diff --git a/src/lib/core/decimal.c b/src/lib/core/decimal.c index 634dd61b0c23bd717ccd690bd34ccd00c1661907..6ef351f814f1a4532b86990a927693e6ba89b079 100644 --- a/src/lib/core/decimal.c +++ b/src/lib/core/decimal.c @@ -172,14 +172,14 @@ decimal_round(decimal_t *dec, int scale) if (scale < 0 || scale > DECIMAL_MAX_DIGITS) return NULL; - if (scale > decimal_scale(dec)) + if (scale >= decimal_scale(dec)) return dec; - int ndig = decimal_precision(dec) - decimal_scale(dec) + scale; + int ndig = MAX(decimal_precision(dec) - decimal_scale(dec) + scale, 1); decContext context = { ndig, /* Precision */ - ndig - 1, /* emax */ - -1, /* emin */ + ndig, /* emax */ + scale != 0 ? -1 : 0, /* emin */ DECIMAL_ROUNDING, /* rounding */ 0, /* no traps */ 0, /* zero status */ diff --git a/test/app/decimal.result b/test/app/decimal.result index 9185e24cc24ea2093fd60bebdb981bb8a93cf368..b53f4e75da7e5bf417d7e1d4bc2e4b28d7aaf9a8 100644 --- a/test/app/decimal.result +++ b/test/app/decimal.result @@ -510,3 +510,21 @@ decimal.trim(a) | --- | - '123.456789' | ... + +-- check correct rounding when scale = 0 +decimal.round(decimal.new(0.9), 0) + | --- + | - '1' + | ... +decimal.round(decimal.new(9.9), 0) + | --- + | - '10' + | ... +decimal.round(decimal.new(99.9), 0) + | --- + | - '100' + | ... +decimal.round(decimal.new(99.4), 0) + | --- + | - '99' + | ... diff --git a/test/app/decimal.test.lua b/test/app/decimal.test.lua index 43229b22756f1dd13c0afc10ed409a2dfa083d88..cee56d5e7048d634de657084f35bdc06246fdf4e 100644 --- a/test/app/decimal.test.lua +++ b/test/app/decimal.test.lua @@ -143,3 +143,9 @@ decimal.trim(decimal.rescale(a, 10)) a = decimal.new('123.456789000000000') a decimal.trim(a) + +-- check correct rounding when scale = 0 +decimal.round(decimal.new(0.9), 0) +decimal.round(decimal.new(9.9), 0) +decimal.round(decimal.new(99.9), 0) +decimal.round(decimal.new(99.4), 0)