From 8aefe626a90e6d1b76177e72ae6b384158ae0369 Mon Sep 17 00:00:00 2001 From: "A. Unique TensorFlower" Date: Wed, 16 Sep 2020 12:41:59 -0700 Subject: [PATCH] Fix micro string formatting bug. Properly handle float fractions with no leading zeros. PiperOrigin-RevId: 332065497 Change-Id: I2e8470ccd7082eee220268593ea3a100888567d1 --- tensorflow/lite/micro/micro_string.cc | 14 ++++++++------ tensorflow/lite/micro/micro_string_test.cc | 9 +++++++++ 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/tensorflow/lite/micro/micro_string.cc b/tensorflow/lite/micro/micro_string.cc index 95a0ae156ae..ad769f69b0e 100644 --- a/tensorflow/lite/micro/micro_string.cc +++ b/tensorflow/lite/micro/micro_string.cc @@ -192,13 +192,15 @@ char* FastFloatToBufferLeft(float f, char* buffer) { // works properly. *current = '0'; - // Shift fraction values and prepent zeros. - for (int i = 0; i < fraction_digits; i++) { - current--; - *(current + leading_zeros) = *current; - *current = '0'; + // Shift fraction values and prepend zeros if necessary. + if (leading_zeros != 0) { + for (int i = 0; i < fraction_digits; i++) { + current--; + *(current + leading_zeros) = *current; + *current = '0'; + } + current += kMaxFractionalDigits; } - current += kMaxFractionalDigits; // Truncate trailing zeros for cleaner logs. Ensure we leave at least one // fractional character for the case when scaled_fraction is 0. diff --git a/tensorflow/lite/micro/micro_string_test.cc b/tensorflow/lite/micro/micro_string_test.cc index 400f908f97f..f69812c5a9e 100644 --- a/tensorflow/lite/micro/micro_string_test.cc +++ b/tensorflow/lite/micro/micro_string_test.cc @@ -120,6 +120,15 @@ TF_LITE_MICRO_TEST(FloatFormatShouldPrintFractionCorrectly) { TF_LITE_MICRO_EXPECT_STRING_EQ(golden, buffer); } +TF_LITE_MICRO_TEST(FloatFormatShouldPrintFractionCorrectlyNoLeadingZeros) { + const int kBufferLen = 24; + char buffer[kBufferLen]; + const char golden[] = "Float: 1.6332993*2^-1"; + int bytes_written = MicroSnprintf(buffer, kBufferLen, "Float: %f", 0.816650); + TF_LITE_MICRO_EXPECT_EQ(static_cast(sizeof(golden)), bytes_written); + TF_LITE_MICRO_EXPECT_STRING_EQ(golden, buffer); +} + TF_LITE_MICRO_TEST(StringFormatOverrunShouldTruncate) { const int kBufferLen = 10; char buffer[kBufferLen];