We've had a few challenges for base conversion, but all of them seem to apply to integer values. Let's do it with real numbers!
The challenge
Inputs:
- A real positive number x, expressed in base 10. This can be taken as a double-precision float or as a string. To avoid precision issues, the number can be assumed to be greater than 10−6 and less than 1015.
- A target base b. This will be an integer from 2 to 36.
- A number of fractional digits n. This will be an integer from 1 to 20.
Output: the representation of x in base b with n fractional digits.
When computing the output expression, the digits beyond the n-th should be truncated (not rounded). For example, x = 3.141592653589793
in base b = 3
is 10.0102110122...
, so for n = 3
the output would be 10.010
(truncation), not 10.011
(rounding).
For x and b that produce a finite number of digits in the fractional part, the equivalent infinite representation (truncated to n digits) is also allowed. For example, 4.5
in decimal can also be represented as 4.49999...
.
Don't worry about floating point errors.
Input and output format
x will be given without leading zeros. If x happens to be an integer you can assume that it will be given with a zero decimal part (3.0
), or without decimal part (3
).
The output is flexible. For example, it can be:
- A string representing the number with a suitable separator (decimal point) between integer and fractional parts. Digits
11
,12
etc (for b beyond 10) can be represented as lettersA
,B
as usual, or as any other distinct characters (please specify). - A string for the integer part and another string for the fractional part.
- Two arrays/lists, one for each part, containing numbers from
0
to35
as digits.
The only restrictions are that the integer and fractional parts can be told apart (suitable separator) and use the same format (for example, no [5, 11]
for the list representing the integer part and ['5', 'B']
for the list representing the fractional part).
Additional rules
- Programs or functions are allowed, in any programming language. Standard loopholes are forbidden.
- Shortest code in bytes wins.
Test cases
Output is shown as a string with digits 0
, ..., 9
, A
, ... , Z
, using .
as decimal separator.
x, b, n -> output(s)
4.5, 10, 5 -> 4.50000 or 4.49999
42, 13, 1 -> 33.0 or 32.C
3.141592653589793, 3, 8 -> 10.01021101
3.141592653589793, 5, 10 -> 3.0323221430
1.234, 16, 12 -> 1.3BE76C8B4395
10.5, 2, 8 -> 1010.10000000 or 1010.01111111
10.5, 3, 8 -> 101.11111111
6.5817645, 20, 10 -> 6.BCE2680000 or 6.BCE267JJJJ
0.367879441171442, 25, 10 -> 0.94N2MGH7G8
12944892982609, 29, 9 -> PPCGROCKS.000000000
42, 13, 1
can we have33
instead of33.0
? \$\endgroup\$n
decimal digits \$\endgroup\$