TDME2  1.9.200
Float.cpp
Go to the documentation of this file.
1 #include <tdme/utilities/Float.h>
2 
3 #include <algorithm>
4 #include <cctype>
5 #include <cstring>
6 #include <string>
7 #include <string_view>
8 
9 #include <tdme/tdme.h>
10 #include <tdme/utilities/Console.h>
12 
13 using std::find_if;
14 using std::isdigit;
15 using std::isnan;
16 using std::stof;
17 using std::string;
18 using std::string_view;
19 using std::to_string;
20 
22 
25 
26 bool Float::is(const string& str) {
27  auto trimmedStr = StringTools::trim(str);
28  int dotCount = 0;
29  return
30  str.empty() == false &&
31  find_if(
32  trimmedStr.begin() + (trimmedStr[0] == '-'?1:0),
33  trimmedStr.end(),
34  [&dotCount](unsigned char c) {
35  return isdigit(c) == 0 && (c != '.' || ++dotCount > 1);
36  }) == trimmedStr.end();
37 }
38 
39 bool Float::viewIs(const string_view& str) {
40  auto trimmedStr = StringTools::viewTrim(str);
41  int dotCount = 0;
42  return
43  str.empty() == false &&
44  find_if(
45  trimmedStr.begin() + (trimmedStr[0] == '-'?1:0),
46  trimmedStr.end(),
47  [&dotCount](unsigned char c) {
48  return isdigit(c) == 0 && (c != '.' || ++dotCount > 1);
49  }
50  ) == trimmedStr.end();
51 }
52 
53 float Float::parse(const string& str) {
54  auto trimmedStr = StringTools::trim(str);
55  if (trimmedStr.empty() == true) return 0.0f;
56  if (trimmedStr == "-") return -0.0f;
57  auto dotCount = 0;
58  auto digitSum = 0;
59  return
60  (str.empty() == false &&
61  find_if(
62  trimmedStr.begin() + (trimmedStr[0] == '-'?1:0),
63  trimmedStr.end(),
64  [&dotCount, &digitSum](unsigned char c) {
65  if (isdigit(c) != 0) digitSum+= c - '0'; return isdigit(c) == 0 && (c != '.' || ++dotCount > 1);
66  }
67  ) == trimmedStr.end()) == true && digitSum > 0?stof(trimmedStr):0.0f;
68 }
69 
70 float Float::viewParse(const string_view& str) {
71  auto trimmedStr = StringTools::viewTrim(str);
72  if (trimmedStr.empty() == true) return 0.0f;
73  if (trimmedStr == "-") return -0.0f;
74  // TODO: we need to do this this way as long there is no from_chars with float
75  if (str.size() > 32) {
76  Console::println("Float::viewParse(): str.size() > 32, returning 0.0f");
77  return 0.0f;
78  }
79  char buf[33];
80  memcpy(buf, &trimmedStr[0], trimmedStr.size());
81  buf[str.size()] = 0;
82  return atof(buf);
83 }
Console class.
Definition: Console.h:29
static void println()
Print new line to console.
Definition: Console.cpp:92
Float class.
Definition: Float.h:27
static bool viewIs(const string_view &str)
Check if given string is a float string.
Definition: Float.cpp:39
static float viewParse(const string_view &str)
Parse float.
Definition: Float.cpp:70
static float parse(const string &str)
Parse float.
Definition: Float.cpp:53
String tools class.
Definition: StringTools.h:22
static const string trim(const string &src)
Trim string.
Definition: StringTools.cpp:51
static const string_view viewTrim(const string_view &src)
Trim string.
Definition: StringTools.cpp:76