Fix micro string formatting bug. Properly handle float fractions with no leading zeros.

PiperOrigin-RevId: 332065497
Change-Id: I2e8470ccd7082eee220268593ea3a100888567d1
This commit is contained in:
A. Unique TensorFlower 2020-09-16 12:41:59 -07:00 committed by TensorFlower Gardener
parent a58bfeef15
commit 8aefe626a9
2 changed files with 17 additions and 6 deletions

View File

@ -192,13 +192,15 @@ char* FastFloatToBufferLeft(float f, char* buffer) {
// works properly. // works properly.
*current = '0'; *current = '0';
// Shift fraction values and prepent zeros. // Shift fraction values and prepend zeros if necessary.
if (leading_zeros != 0) {
for (int i = 0; i < fraction_digits; i++) { for (int i = 0; i < fraction_digits; i++) {
current--; current--;
*(current + leading_zeros) = *current; *(current + leading_zeros) = *current;
*current = '0'; *current = '0';
} }
current += kMaxFractionalDigits; current += kMaxFractionalDigits;
}
// Truncate trailing zeros for cleaner logs. Ensure we leave at least one // Truncate trailing zeros for cleaner logs. Ensure we leave at least one
// fractional character for the case when scaled_fraction is 0. // fractional character for the case when scaled_fraction is 0.

View File

@ -120,6 +120,15 @@ TF_LITE_MICRO_TEST(FloatFormatShouldPrintFractionCorrectly) {
TF_LITE_MICRO_EXPECT_STRING_EQ(golden, buffer); 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<int>(sizeof(golden)), bytes_written);
TF_LITE_MICRO_EXPECT_STRING_EQ(golden, buffer);
}
TF_LITE_MICRO_TEST(StringFormatOverrunShouldTruncate) { TF_LITE_MICRO_TEST(StringFormatOverrunShouldTruncate) {
const int kBufferLen = 10; const int kBufferLen = 10;
char buffer[kBufferLen]; char buffer[kBufferLen];