* This function prints a floating-point value in a format similar to * printf("%.7g") on a single-precision machine or printf("%.9g") on a * double-precision machine. The 7th digit won't always be totally correct * in single-precision operation (for that level of accuracy, a more * complicated algorithm would be needed). */
| 332 | * complicated algorithm would be needed). |
| 333 | */ |
| 334 | void UnityPrintFloat(const UNITY_DOUBLE input_number) |
| 335 | { |
| 336 | #ifdef UNITY_INCLUDE_DOUBLE |
| 337 | static const int sig_digits = 9; |
| 338 | static const UNITY_INT32 min_scaled = 100000000; |
| 339 | static const UNITY_INT32 max_scaled = 1000000000; |
| 340 | #else |
| 341 | static const int sig_digits = 7; |
| 342 | static const UNITY_INT32 min_scaled = 1000000; |
| 343 | static const UNITY_INT32 max_scaled = 10000000; |
| 344 | #endif |
| 345 | |
| 346 | UNITY_DOUBLE number = input_number; |
| 347 | |
| 348 | /* print minus sign (does not handle negative zero) */ |
| 349 | if (number < 0.0f) |
| 350 | { |
| 351 | UNITY_OUTPUT_CHAR('-'); |
| 352 | number = -number; |
| 353 | } |
| 354 | |
| 355 | /* handle zero, NaN, and +/- infinity */ |
| 356 | if (number == 0.0f) |
| 357 | { |
| 358 | UnityPrint("0"); |
| 359 | } |
| 360 | else if (UNITY_IS_NAN(number)) |
| 361 | { |
| 362 | UnityPrint("nan"); |
| 363 | } |
| 364 | else if (UNITY_IS_INF(number)) |
| 365 | { |
| 366 | UnityPrint("inf"); |
| 367 | } |
| 368 | else |
| 369 | { |
| 370 | UNITY_INT32 n_int = 0; |
| 371 | UNITY_INT32 n; |
| 372 | int exponent = 0; |
| 373 | int decimals; |
| 374 | int digits; |
| 375 | char buf[16] = {0}; |
| 376 | |
| 377 | /* |
| 378 | * Scale up or down by powers of 10. To minimize rounding error, |
| 379 | * start with a factor/divisor of 10^10, which is the largest |
| 380 | * power of 10 that can be represented exactly. Finally, compute |
| 381 | * (exactly) the remaining power of 10 and perform one more |
| 382 | * multiplication or division. |
| 383 | */ |
| 384 | if (number < 1.0f) |
| 385 | { |
| 386 | UNITY_DOUBLE factor = 1.0f; |
| 387 | |
| 388 | while (number < (UNITY_DOUBLE)max_scaled / 1e10f) { number *= 1e10f; exponent -= 10; } |
| 389 | while (number * factor < (UNITY_DOUBLE)min_scaled) { factor *= 10.0f; exponent--; } |
| 390 | |
| 391 | number *= factor; |