Skip to content

Commit 92fce04

Browse files
authored
Merge pull request #1033 from netfs/r1.9
Fix erroneous formatting of numbers that are larger than 6 digits.
2 parents 85c595e + fca72ce commit 92fce04

File tree

2 files changed

+36
-6
lines changed

2 files changed

+36
-6
lines changed

tensorflow_serving/util/json_tensor.cc

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -700,12 +700,16 @@ bool WriteDecimal(RapidJsonWriter* writer, dtype val) {
700700
string decimal_str;
701701
if (std::isfinite(val)) {
702702
decimal_str = absl::StrCat(val);
703-
// Add trailing '.0' for whole numbers. StrCat() formats whole numbers
704-
// without one. This can lead to lists containing mix of decimal and
705-
// whole numbers -- making it difficult for consumers to pick the
706-
// correct type to store these numbers (note, JSON does not have
707-
// metadata to describe types. These are inferred from the tokens).
708-
if (decimal_str.find('.') == string::npos) {
703+
// Add trailing '.0' for whole numbers and those not in scientific notation.
704+
// StrCat() formats numbers in six-digit (printf "%g"), numbers like 9000000
705+
// and .00003 get written as 9e+06 and 3e-05 (scientific notation).
706+
//
707+
// Not adding '.0' can lead to lists containing mix of decimal and whole
708+
// numbers -- making it difficult for consumers to pick the correct type to
709+
// store these numbers (note, JSON does not have metadata to describe types.
710+
// These are inferred from the tokens).
711+
if (decimal_str.find('.') == string::npos &&
712+
decimal_str.find('e') == string::npos) {
709713
absl::StrAppend(&decimal_str, ".0");
710714
}
711715
} else if (std::isnan(val)) {

tensorflow_serving/util/json_tensor_test.cc

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -546,6 +546,32 @@ TEST(JsontensorTest, FromJsonSingleBytesTensor) {
546546
]})"));
547547
}
548548

549+
// Tests StrCat() six-digit precision float output is correctly
550+
// represented in the final (output) JSON string.
551+
TEST(JsontensorTest, FromJsonSingleFloatTensorSixDigitPrecision) {
552+
TensorMap tensormap;
553+
ASSERT_TRUE(TextFormat::ParseFromString(R"(
554+
dtype: DT_FLOAT
555+
tensor_shape {
556+
dim { size: 2 }
557+
dim { size: 2 }
558+
}
559+
float_val: 9000000
560+
float_val: 999999
561+
float_val: .0003
562+
float_val: .00003
563+
)",
564+
&tensormap["float_tensor"]));
565+
566+
string json;
567+
TF_EXPECT_OK(MakeJsonFromTensors(tensormap, &json));
568+
TF_EXPECT_OK(CompareJsonAllValuesAsStrings(json, R"({
569+
"predictions": [
570+
[9e+06, 999999.0],
571+
[0.0003, 3e-05]
572+
]})"));
573+
}
574+
549575
TEST(JsontensorTest, FromJsonSingleFloatTensorNonFinite) {
550576
TensorMap tensormap;
551577
ASSERT_TRUE(TextFormat::ParseFromString(R"(

0 commit comments

Comments
 (0)