Skip to content

Open Source alternative to Algolia + Pinecone and an Easier-to-Use alternative to ElasticSearch ⚡ 🔍 ✨ Fast, typo tolerant, in-memory fuzzy Search Engine for building delightful search experiences

Fix float validation to handle scientific notation.

Kishore Nallan7b59f10d4639
diff --git a/include/string_utils.h b/include/string_utils.h
index 2252ad59..43e4fbcd 100644
--- a/include/string_utils.h
+++ b/include/string_utils.h
@@ -117,26 +117,14 @@ struct StringUtils {
return escaped.str();
}
- // See: https://stackoverflow.com/a/19751887/131050
static bool is_float(const std::string &s) {
- std::string::const_iterator it = s.begin();
- bool decimalPoint = false;
- size_t minSize = 0;
- if(s.size() > 0 && (s[0] == '-' || s[0] == '+')) {
- it++;
- minSize++;
- }
-
- while(it != s.end()){
- if(*it == '.') {
- if(!decimalPoint) decimalPoint = true;
- else break;
- } else if(!std::isdigit(*it) && ((*it!='f') || it+1 != s.end() || !decimalPoint)) {
- break;
- }
- ++it;
+ try {
+ size_t num_chars_processed = 0;
+ std::stof(s, &num_chars_processed);
+ return num_chars_processed == s.size();
+ } catch(...) {
+ return false;
}
- return s.size() > minSize && it == s.end();
}
// Adapted from: http://stackoverflow.com/a/2845275/131050
diff --git a/test/string_utils_test.cpp b/test/string_utils_test.cpp
index 5d800afe..4ba2af73 100644
--- a/test/string_utils_test.cpp
+++ b/test/string_utils_test.cpp
@@ -101,6 +101,19 @@ TEST(StringUtilsTest, ShouldComputeSHA256) {
StringUtils::hash_sha256("791a27668b3e01fc6ab3482b6e6a36255154df3ecd7dcec").c_str());
}
+TEST(StringUtilsTest, ShouldCheckFloat) {
+ ASSERT_TRUE(StringUtils::is_float("0.23"));
+ ASSERT_TRUE(StringUtils::is_float("9.872019290924072e-07"));
+
+ ASSERT_FALSE(StringUtils::is_float("4.2f"));
+ ASSERT_FALSE(StringUtils::is_float("-5.3f"));
+ ASSERT_FALSE(StringUtils::is_float("+6.2f"));
+ ASSERT_FALSE(StringUtils::is_float("0.x87"));
+ ASSERT_FALSE(StringUtils::is_float("1.0.0"));
+ ASSERT_FALSE(StringUtils::is_float("2f"));
+ ASSERT_FALSE(StringUtils::is_float("2.0f1"));
+}
+
TEST(StringUtilsTest, ShouldParseQueryString) {
std::map<std::string, std::string> qmap;