Convert decimal number to rational: Difference between revisions

(Added 11l)
Line 1,320:
"3/4"
]</pre>
 
=={{header|jq}}==
'''Works with [[#jq|jq]]''' (*)
 
'''Works with gojq, the Go implementation of jq'''
 
The following definition of `number_to_r` can be used for JSON numbers in general, as illustrated by the examples.
 
This entry assumes the availability
of two functions (`r/2` and `power/1`) as defined in
the "rational" module
at [[Arithmetic/Rational#jq]], which also provides a definition
for `rpp/0`, a pretty-printer used in the examples.
 
(*) With the caveat that the C implementation of jq does not support unlimited-precision integer arithmetic.
 
<lang jq># include "rational"; # a reminder that r/2 and power/1 are required
 
# Input: any JSON number, not only a decimal
# Output: a rational, constructed using r/2
# Requires power/1 (to take advantage of gojq's support for integer arithmetic)
# and r/2 (for rational number constructor)
def number_to_r:
 
# input: a decimal string
# $in - either null or the original input
# $e - the integer exponent of the original number, or 0
def dtor($in; $e):
index(".") as $ix
| if $in and ($ix == null) then $in
else (if $ix then sub("[.]"; "") else . end | tonumber) as $n
| (if $ix then ((length - ($ix+1)) - $e) else - $e end) as $p
| if $p >= 0
then r( $n; 10|power($p))
else r( $n * (10|power(-$p)); 1)
end
end;
. as $in
| tostring
| if (test("[Ee]")|not) then dtor($in; 0)
else capture("^(?<s>[^eE]*)[Ee](?<e>.*$)")
| (.e | if length > 0 then tonumber else 0 end) as $e
| .s | dtor(null; $e)
end ;</lang>
'''Examples'''
<lang jq>0.9054054,
0.518518,
0.75,
1e308
| "\(.) → \(number_to_r | rpp)"</lang>
{{out}}
<pre>
0.9054054 → 4527027 // 5000000
0.518518 → 259259 // 500000
0.75 → 3 // 4
1e+308 → 100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 // 1
</pre>
 
=={{header|Julia}}==
2,451

edits