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
3#ifndef TETL_STRINGS_FROM_FLOATING_POINT_HPP
4#define TETL_STRINGS_FROM_FLOATING_POINT_HPP
5
8#include <etl/_math/ipow.hpp>
9#include <etl/_span/span.hpp>
11
12namespace etl::strings {
13
17
18enum struct from_floating_point_error : unsigned char {
21};
22
27
28template <floating_point Float, from_floating_point_options Options = from_floating_point_options{}>
29[[nodiscard]] constexpr auto from_floating_point(Float val, span<char> out, int precision) -> from_floating_point_result
30{
31 using int_type = conditional_t<(sizeof(Float) > 4), long long, long>;
32
33 constexpr auto toString = [](int_type x, char* str, int numDigits) -> int {
34 int i = 0;
35 while (x) {
36 str[i++] = (x % 10) + '0';
37 x = x / 10;
38 }
39
40 // If number of digits required is more, then
41 // add 0s at the beginning
42 while (i < numDigits) {
43 str[i++] = '0';
44 }
45
46 etl::reverse(str, str + i);
47 str[i] = '\0';
48 return i;
49 };
50
51 auto* res = out.data();
52
53 auto const whole = static_cast<int_type>(val);
54 auto const frac = val - static_cast<Float>(whole);
55 auto const pos = toString(whole, res, 0);
56
57 if (precision == 0) {
58 return {};
59 }
60
61 // Get the value of fraction part upto given no.
62 // of points after dot. The third parameter
63 // is needed to handle cases like 233.007
64 auto part = static_cast<int_type>(frac * static_cast<Float>(etl::ipow<10>(precision)));
65 res[pos] = '.';
66 toString(part, res + pos + 1, precision);
67
68 return {.end = res + pos};
69}
70
71} // namespace etl::strings
72
73#endif // TETL_STRINGS_FROM_FLOATING_POINT_HPP
The concept floating_point<T> is satisfied if and only if T is a floating-point type.
Definition floating_point.hpp:13
constexpr auto reverse(BidirIt first, BidirIt last) -> void
Reverses the order of the elements in the range [first, last).
Definition reverse.hpp:16
Definition find.hpp:8
constexpr auto from_floating_point(Float val, span< char > out, int precision) -> from_floating_point_result
Definition from_floating_point.hpp:29
from_floating_point_error
Definition from_floating_point.hpp:18
@ overflow
Definition from_floating_point.hpp:20
@ none
Definition from_floating_point.hpp:19
typename conditional< B, T, F >::type conditional_t
Definition conditional.hpp:21
constexpr auto ipow(Int base, Int exponent) noexcept -> Int
Definition ipow.hpp:11
A non-owning view over a contiguous sequence of objects.
Definition span.hpp:83
Definition from_floating_point.hpp:14
bool terminate_with_null
Definition from_floating_point.hpp:15
Definition from_floating_point.hpp:23
char * end
Definition from_floating_point.hpp:24
from_floating_point_error error
Definition from_floating_point.hpp:25