Getting the number of decimal places: Difference between revisions
Getting the number of decimal places (view source)
Revision as of 23:21, 19 April 2024
, 1 month ago→{{header|Phix}}: use pygments
Drkameleon (talk | contribs) (added Arturo) |
m (→{{header|Phix}}: use pygments) |
||
(16 intermediate revisions by 8 users not shown) | |||
Line 1:
{{draft task}}
;Task:
Write a program (function) to get the number of
Line 113:
1E-10 has 10 decimals
1.23456789E+10 has 0 decimals
</pre>
=={{header|Ada}}==
<syntaxhighlight lang="ada">
-- Report the number of decimal places in a number
-- J. Carter 2023 Apr
-- I presume the input is a String containing the image of the value; the test values of 12.345 & 12.3450 represent the same number,
-- and so would give the same result otherwise
with Ada.Strings.Fixed;
with Ada.Text_IO;
procedure Decimal_Places is
function Num_Places (Number : in String) return Natural;
-- Returns the number of decimal places in the numeric image in Number
function Num_Places (Number : in String) return Natural is
Dot : constant Natural := Ada.Strings.Fixed.Index (Number, ".");
begin -- Num_Places
if Dot = 0 then
return 0;
end if;
return Number'Last - Dot;
end Num_Places;
Test_1 : constant String := "12.345";
Test_2 : constant String := "12.3450";
begin -- Decimal_Places
Ada.Text_IO.Put_Line (Item => Test_1 & (1 .. 10 - Test_1'Length => ' ') & Num_Places (Test_1)'Image);
Ada.Text_IO.Put_Line (Item => Test_2 & (1 .. 10 - Test_2'Length => ' ') & Num_Places (Test_2)'Image);
end Decimal_Places;
</syntaxhighlight>
{{out}}
<pre>
12.345 3
12.3450 4
</pre>
Line 168 ⟶ 207:
=={{header|C}}==
<syntaxhighlight lang="c">#include <stdio.h>
#include <string.h>
int findNumOfDec(
return strlen(s + pos);
}
void test(
int num = findNumOfDec(
printf("%s has %d decimal%s\n", s, num, p);
}
int main() {
test("12
test("12.
test("12.
test("12.
test("12.
test(
char str[64];
sprintf(str, "%f", 1.2345e+54);
test(str);
return 0;
}</syntaxhighlight>
{{out}}
<pre>
12
12.
12.
12.
12.3450 has 4 decimals
12.34555555555555555555 has 20 decimals
1234500000000000060751116919315055127939946206157864960.000000 has 6 decimals
</pre>
=={{header|C++}}==
{{trans|C}}
<syntaxhighlight lang="cpp">#include <
#include <
int findNumOfDec(
int pos = 0;
while (s[pos] && s[pos++] != '.') {}
return strlen(s + pos);
}
void test(
const char *p = num != 1 ? "s" : "";
std::cout << s << " has " << num << " decimal" << p << "\n";
}
int main() {
test("12
test("12.
test("12.
test("12.
test("12.
test(
char str[64];
sprintf(str, "%f", 1.2345e+54);
test(str);
return 0;
}</syntaxhighlight>
{{out}}
<pre>
12
12.
12.345 has 3 decimals
12.
12.34555555555555555555 has 20 decimals
1234500000000000060751116919315055127939946206157864960.000000 has 6 decimals
</pre>
=={{header|EasyLang}}==
<syntaxhighlight>
func ndec n .
while abs (n - floor (n + 1e-15)) > 1e-15
n *= 10
r += 1
.
return r
.
for i in [ 0.00000000000001 12.345 12.3450 1.1 0.1234567 ]
write ndec i & " "
.
</syntaxhighlight>
{{out}}
<pre>
14 3 3 1 7
</pre>
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
//Getting the number of decimal places. Nigel Galloway: March 23rd., 2023.
let fN g=let n,g=Seq.length g,g|>Seq.tryFindIndex((=)'.') in match g with Some g->n-g-1 |_->0
["12";"12.00";"12.345";"12.3450";"12.34500"]|>List.iter(fN>>printfn "%d")
</syntaxhighlight>
{{out}}
<pre>
0
2
3
4
5
</pre>
=={{header|FreeBASIC}}==
Line 280 ⟶ 335:
12.345677 has 6 decimals
0.142857142857142 has 15 decimals</pre>
=={{header|Go}}==
Line 369 ⟶ 423:
<pre>[1,3,3,12,15,7]</pre>
=={{header|Java}}==
<syntaxhighlight lang="java">
int decimalPlaces(double value) {
String string = String.valueOf(value);
return string.length() - (string.indexOf('.') + 1);
}
</syntaxhighlight>
Or
<syntaxhighlight lang="java">public static int findNumOfDec(double x){
String str = String.valueOf(x);
Line 374 ⟶ 435:
else return (str.substring(str.indexOf('.')).length() - 1);
}</syntaxhighlight>
=={{header|jq}}==
The current (March 2023) official releases of jq, gojq, fq, and jaq cannot be relied upon
to preserve the literal form of numbers, and in particular they drop the
final 0 of `12.3450` when presented as a number. However, the current "master" version of jq retains
the literal form of numbers. Accordingly, both the numeric and the string forms of 12.3450 are included in the suite of test
cases, and two sets of results are presented below.
<syntaxhighlight lang=jq>
def number_decimal_digits:
. as $in
| def nil: . == null or . == "";
def nodecimal: # e.g. 12 or 12e-2
capture("^[-+]?[0-9]*([eE](?<sign>[-+]?)(?<p>[0-9]+))?$")
| if .sign|nil then 0
elif .p|nil then "internal error: \($in)"|error
else .p|tonumber
end;
tostring
| nodecimal
// capture("^[-+]?[0-9]*[.](?<d>[0-9]+)([eE](?<sign>[-+]?)(?<p>[0-9]+))?$") # has decimal
// null
| if type == "number" then .
elif not then 0
elif .d|nil then 0
elif (.sign|nil) and .p == null then .d|length
elif (.sign|nil) or .sign == "+" then [0, (.d|length) - (.p|tonumber)] | max
elif .sign == "-" then (.d|length) + (.p|tonumber)
else "internal error: \($in)"|error
end ;
def examples:
[12.345, 3],
[12.3450, 4],
["12.3450", 4],
[1e-2, 2],
[1.23e2, 0];
def task:
examples
| (first|number_decimal_digits) as $d
| if $d == last then empty
else "\(first) has \(last) decimal places but the computed value is \($d)"
end;
task, "Bye."
</syntaxhighlight>
{{output}}
Using gojq:
<pre>
12.345 has 4 decimal places but the computed value is 3
Bye.
</pre>
Using jq post-1.6:
<pre>
Bye.
</pre>
=={{header|Julia}}==
Line 510 ⟶ 628:
=={{header|Phix}}==
<!--
<syntaxhighlight lang="phix">
constant fracfmt = iff(machine_bits()=32?"%.14g":"%.18g")
function num_decimals(object o)
integer nd = -1
string s, t
if integer(o) then
nd = 0
s = sprintf("%d",o)
elsif atom(o) then
s = sprintf("%.19g",o)
o -= trunc(o)
if o=0 then
else
t = sprintf(fracfmt,o)
end if
elsif string(o) then
s = o
t = s
else
crash("unknown type")
end if
if nd=-1 then
integer e = find('e',t)
if e then
{t,e} = {t[1..e-1],to_number(t[e+1..$])}
end if
integer dot = find('.',t)
nd = iff(dot?max(length(t)-dot-e,0):max(-e,0))
end if
s = shorten(s,"digits",5)
return {s,nd}
end function
sequence tests = {"0.00100", 0.00100, 001.805, 1/3, 12, 12.345, 12.345555555555,
"12.3450", "12.34555555555555555555", 12.345e53, 1.2345e-08,
"12.345e53", "1.2345e-08", "0.1234567890987654321",
"124093581919.648947697827373650380188008224280338254175148904323577880859375"}
for i=1 to length(tests) do
printf(1,"%25s has %d decimals\n",num_decimals(tests[i]))
end for
</syntaxhighlight>
{{out}}
32 bit
Line 825 ⟶ 944:
<pre>
4
</pre>
'''Another version'''
<syntaxhighlight lang="ring">
decimals(4)
num = 5.1945
strnum = string(num)
pos = substr(strnum,".")
dec = len(strnum) - pos
see "Number of decimals: " + dec + nl
</syntaxhighlight>
{{out}}
<pre>
Number of decimals: 4
</pre>
=={{header|RPL}}==
≪ DUP MANT →STR SIZE SWAP XPON - 2 - 0 MAX
≫ ''''NDEC'''' STO
≪ { 12 120 12.345 12.345677 1.23E-20 1.23E20 } → cases
≪ { } 1 cases SIZE '''FOR''' j
cases j GET '''NDEC''' + '''NEXT'''
≫ ≫ ''''TASK'''' STO
{{out}}
<pre>
1: { 0 0 3 6 22 0 }
</pre>
Line 875 ⟶ 1,021:
Converting the fourth example to a Rat or BigRat object wouldn't help as the constructor for those classes automatically reduces the numerator and denominator to their lowest terms. BigRat would work for the fifth example but the argument would have to be passed as a string anyway so we might as well just parse the string.
<syntaxhighlight lang="
var getNumDecimals = Fn.new { |n|
|