From 9653fbf7ac1321573de1d6c0de41c4c423fbd5ff Mon Sep 17 00:00:00 2001 From: jsalling Date: Sat, 24 Sep 2016 14:16:26 -0500 Subject: [PATCH] Use an integer cast to print floating point numbers more precisely Improve printing six decimal places, remove trailing 0's, fix the carry when numbers like 0.9999999 round up and print leading zeros in the decimal The first attempt at printing floats had precision issues where the last few digits would often be wrong. This next approach may yield a better algorithm for numbers less than 4.29 billion, those that fit in 32 bits. --- src/unity.c | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/unity.c b/src/unity.c index e1294c3..636881b 100644 --- a/src/unity.c +++ b/src/unity.c @@ -284,6 +284,33 @@ void UnityPrintFloat(_UD number) _U_UINT exponent = 0; int scifmt; _U_UINT i; + _UU32 integer_part; + _UD fraction_part; + // if (number <= 0xFFFFFFFF) /* Fits in an integer */ + { + integer_part = (_UU32)number; + fraction_part = number - integer_part; + } + + _U_UINT fraction_bits = (_U_UINT)(fraction_part * 1000000.0f + 0.5f); + if (fraction_bits == 1000000) + { + fraction_bits = 0; + integer_part += 1; + } + _U_UINT divisor_int = 100000; + + UnityPrintNumberUnsigned(integer_part); + UNITY_OUTPUT_CHAR('.'); + /* now mod and print, then divide divisor */ + do + { + UNITY_OUTPUT_CHAR((char)('0' + (fraction_bits / divisor_int))); + fraction_bits %= divisor_int; + if (fraction_bits == 0) break; // Truncate trailing 0's + divisor_int /= 10; + } while (divisor_int > 0); + UNITY_OUTPUT_CHAR(' '); while (number / divisor >= 10.0f) { -- GitLab