From 153bf23a9fc58f696ebe5a10f617d6ee7b6885fa Mon Sep 17 00:00:00 2001 From: Jon Michael Aanes Date: Fri, 9 Jun 2017 16:57:21 +0200 Subject: [PATCH] Some numbers very close to a short representation will now use that representation. --- number.lua | 9 ++++++++- test/test_number.lua | 10 ++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/number.lua b/number.lua index d0d81e8..9bc639a 100644 --- a/number.lua +++ b/number.lua @@ -149,8 +149,15 @@ function format_num (n, shorthand) local a = { special_number_tests.est(n) } if a[1] then for i = 1, #a do a[i] = math.floor(a[i] + 0.5) end - if n == special_number_tests.real(unpack(a)) then + local num = special_number_tests.real(unpack(a)) + if num == n then alternative_repr( special_number_tests[shorthand and 'short' or 'repr'](unpack(a)) ) + elseif num then + local repr = special_number_tests[shorthand and 'short' or 'repr'](unpack(a)) + local native_precise = tonumber(('%'..utf8.width(repr)..'f'):format(n)) + if math.abs(num - n) <= math.abs( native_precise - n ) then + alternative_repr( repr ) + end end end end diff --git a/test/test_number.lua b/test/test_number.lua index a4a1ac9..950f97c 100644 --- a/test/test_number.lua +++ b/test/test_number.lua @@ -82,6 +82,16 @@ number_test { expect = '0.65', } +number_test { + input = 2.05, + expect = '2.05', +} + +number_test { + input = 2.0512523, + expect = '2.0512523', +} + -------------------------------------------------------------------------------- -- Fractions