Getting the number of decimal places

From Rosetta Code
Revision as of 20:28, 12 August 2020 by Thundergnat (talk | contribs) (→‎{{header|Raku}}: Add a Raku example, though I think the task is pretty bogus)
Getting the number of decimal places is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Write a program (function) to get the number of decimals in a given number.

Examples:

for num = 12.345 decimals = 3 and for num = 12.3450 decimals = 4

Raku

Works with: Rakudo version 2020.07

Raku does not specifically have a "decimal" number type, however we can easily determine the fractional precision of a rational number. It is somewhat touchy-feely for floating point numbers; (what is the fractional precision for 2.45e-12?), it's pretty pointless for Integers; (zero, aalllways zero...), but Rats (rationals) are doable. Note that these are (mostly) actual numerics, not numeric strings. The exception is '12.3450'. That is a numeric string since actual numerics automatically truncate non-significant trailing zeros. If you want to retain them, you need to pass the value as a string. (As below.)

<lang perl6>use Rat::Precise;

printf "Fractional precision: %-2s || Number: %s\n", (.split('.')[1] // ).chars, $_

   for 9, 12.345, '12.3450', 0.1234567890987654321, (1.5**63).precise;

</lang>

Output:
Fractional precision: 0  || Number: 9
Fractional precision: 3  || Number: 12.345
Fractional precision: 4  || Number: 12.3450
Fractional precision: 19 || Number: 0.1234567890987654321
Fractional precision: 63 || Number: 124093581919.648947697827373650380188008224280338254175148904323577880859375

Ring

<lang ring>

  1. Testing the function

decimals(2) # Unsensitive to the default setting of decimals n = 5.1945 ? NbrOfDecimals(n) # Gives 4

func NbrOfDecimals(n) nTemp = 1 nNbrOfDecimals = 0 while True if nNbrOfDecimals < 9 nNbrOfDecimals++ nTemp *= 10 nTemp1 = n * nTemp - ceil( n * nTemp ) if nTemp1 = 0 return nNbrOfDecimals ok else raise("Acceeding the maximum number of 9 decimals!") ok end </lang>

Output:
4