tetl 0.1.0
Embedded Template Library
Loading...
Searching...
No Matches
from_floating_point.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: BSL-1.0
2// SPDX-FileCopyrightText: Copyright (C) 2024 Tobias Hienzsch
3
4#ifndef TETL_STRINGS_FROM_FLOATING_POINT_HPP
5#define TETL_STRINGS_FROM_FLOATING_POINT_HPP
6
7#include <etl/_algorithm/reverse.hpp>
8#include <etl/_concepts/floating_point.hpp>
9#include <etl/_math/ipow.hpp>
10#include <etl/_span/span.hpp>
11#include <etl/_type_traits/conditional.hpp>
12
13namespace etl::strings {
14
17};
18
19enum struct from_floating_point_error : unsigned char {
20 none,
22};
23
25 char* end{nullptr};
27};
28
29template <floating_point Float, from_floating_point_options Options = from_floating_point_options{}>
30[[nodiscard]] constexpr auto from_floating_point(Float val, span<char> out, int precision) -> from_floating_point_result
31{
32 using int_type = conditional_t<(sizeof(Float) > 4), long long, long>;
33
34 constexpr auto toString = [](int_type x, char* str, int numDigits) -> int {
35 int i = 0;
36 while (x) {
37 str[i++] = static_cast<char>((x % 10) + int_type('0'));
38 x = x / 10;
39 }
40
41 // If number of digits required is more, then
42 // add 0s at the beginning
43 while (i < numDigits) {
44 str[i++] = '0';
45 }
46
47 etl::reverse(str, str + i);
48 str[i] = '\0';
49 return i;
50 };
51
52 auto* res = out.data();
53
54 auto const whole = static_cast<int_type>(val);
55 auto const frac = val - static_cast<Float>(whole);
56 auto const pos = toString(whole, res, 0);
57
58 if (precision == 0) {
59 return {};
60 }
61
62 // Get the value of fraction part upto given no.
63 // of points after dot. The third parameter
64 // is needed to handle cases like 233.007
65 auto part = static_cast<int_type>(frac * static_cast<Float>(etl::ipow<10>(precision)));
66 res[pos] = '.';
67 toString(part, res + pos + 1, precision);
68
69 return {.end = res + pos};
70}
71
72} // namespace etl::strings
73
74#endif // TETL_STRINGS_FROM_FLOATING_POINT_HPP
constexpr auto reverse(BidirIt first, BidirIt last) -> void
Reverses the order of the elements in the range [first, last).
Definition reverse.hpp:17
Definition find.hpp:9
constexpr auto from_floating_point(Float val, span< char > out, int precision) -> from_floating_point_result
Definition from_floating_point.hpp:30
from_floating_point_error
Definition from_floating_point.hpp:19
Definition adjacent_find.hpp:9
constexpr auto ipow(decltype(Base) exponent) noexcept -> decltype(Base)
Definition ipow.hpp:22
constexpr auto data() const noexcept -> pointer
Returns a pointer to the beginning of the sequence.
Definition span.hpp:225
Definition from_floating_point.hpp:15
bool terminate_with_null
Definition from_floating_point.hpp:16
Definition from_floating_point.hpp:24
char * end
Definition from_floating_point.hpp:25
from_floating_point_error error
Definition from_floating_point.hpp:26