[ADT] Add llvm::to_float
Summary:
The function matches the interface of llvm::to_integer, but as we are
calling out to a C library function, I let it take a Twine argument, so
we can avoid a string copy at least in some cases.
I add a test and replace a couple of existing uses of strtod with this
function.
Reviewers: zturner
Subscribers: llvm-commits
Differential Revision: https://reviews.llvm.org/D34518
llvm-svn: 306096
diff --git a/llvm/unittests/ADT/StringExtrasTest.cpp b/llvm/unittests/ADT/StringExtrasTest.cpp
index 2cc9cad..8f06f1e 100644
--- a/llvm/unittests/ADT/StringExtrasTest.cpp
+++ b/llvm/unittests/ADT/StringExtrasTest.cpp
@@ -65,4 +65,22 @@
EvenBytes.size());
EXPECT_EQ(EvenStr, toHex(EvenData));
EXPECT_EQ(EvenData, fromHex(EvenStr));
-}
\ No newline at end of file
+}
+
+TEST(StringExtrasTest, to_float) {
+ float F;
+ EXPECT_TRUE(to_float("4.7", F));
+ EXPECT_FLOAT_EQ(4.7, F);
+
+ double D;
+ EXPECT_TRUE(to_float("4.7", D));
+ EXPECT_DOUBLE_EQ(4.7, D);
+
+ long double LD;
+ EXPECT_TRUE(to_float("4.7", LD));
+ EXPECT_DOUBLE_EQ(4.7, LD);
+
+ EXPECT_FALSE(to_float("foo", F));
+ EXPECT_FALSE(to_float("7.4 foo", F));
+ EXPECT_FLOAT_EQ(4.7, F); // F should be unchanged
+}