cgv
Loading...
Searching...
No Matches
number_format.cxx
1#include "number_format.h"
2
3#include <cmath>
4
5#include "convert_string.h"
6#include "scan.h"
7
8namespace cgv {
9namespace utils {
10
11std::string number_format::convert(float value) const {
12 std::string s;
13
14 if(decimal_integers) {
15 s = std::to_string(static_cast<int>(std::round(value)));
16 } else {
17 s = cgv::utils::to_string(value, -1, precision, fixed);
18 if(!trailing_zeros && s.length() > 1)
20 }
21
22 if(grouping) {
23 std::string sign;
24 if(!s.empty() && s.front() == '-' || s.front() == '+') {
25 sign = s.front();
26 s = s.substr(1);
27 }
28
29 std::string suffix;
30 for(size_t i = 0; i < s.size(); ++i) {
31 if(!std::isdigit(s[i])) {
32 suffix = s.substr(i);
33 s = s.substr(0, i);
34 break;
35 }
36 }
37 s = apply_grouping(s);
38 s = sign + s + suffix;
39 }
40
41 return s;
42}
43
44void number_format::precision_from_range(float first, float last) {
45 const float delta = std::abs(last - first);
46 precision = 0;
47
48 float limit = 1.0f;
49 unsigned max_precision = 7;
50 for(unsigned i = 1; i <= max_precision; ++i) {
51 if(delta > limit || i == max_precision) {
52 precision = i;
53 break;
54 }
55 limit /= 2.0f;
56 }
57}
58
59std::string number_format::apply_grouping(const std::string& value) const {
60 if(group_size <= 0)
61 return value;
62
63 std::vector<std::string> parts;
64 int i = value.length();
65 int g = group_size;
66 size_t length = 0;
67
68 while(i > 0) {
69 if(length + g + 1 > value.length())
70 g = std::max(static_cast<size_t>(1), value.length() - length);
71 i -= g;
72 parts.push_back(value.substr(i, g));
73 length += g;
74 if(length > value.length())
75 break;
76 }
77
78 std::reverse(parts.begin(), parts.end());
79 return cgv::utils::join(parts, group_separator);
80}
81
82} // namespace utils
83} // namespace cgv
Helper functions to convert numeric types into strings using std streams.
std::string join(const InputIt first, const InputIt last, const std::string &separator, bool trailing_separator=false)
Concatenate elements in the range [first, last) to a std::string.
Definition algorithm.h:146
std::string to_string(const std::string &v, unsigned int w, unsigned int p, bool)
specialization of conversion from string to strings
std::string & rtrim(std::string &str, const std::string &chars)
trim white space or other characters from end of string
Definition scan.cxx:785
this header is dependency free
Definition print.h:11
Helper functions to process strings.