3
$\begingroup$

I want to truncate a simple number to n decimal digits. For example, 2/3. I used

f[x_, n_] := N[IntegerPart[x 10^n]/10^n]

but I get

f[2/3, 20] = 0.666667

Is there a way to get

f[2/3, 20] = 0.66666666666666666666 ?

I have searched a lot but I haven't really found an answer. I am looking for something like N or Round for truncation.

$\endgroup$
4
  • $\begingroup$ just try N[2/3, 20] $\endgroup$
    – ZaMoC
    Commented Nov 27, 2018 at 12:10
  • $\begingroup$ N rounds the last decimal digit. I get N[2/3, 20] = 0.66666666666666666667 $\endgroup$
    – Alex
    Commented Nov 27, 2018 at 12:12
  • 1
    $\begingroup$ You probably want to use RealDigits[2/3, 10, 20] $\endgroup$
    – Carl Lange
    Commented Nov 27, 2018 at 12:18
  • $\begingroup$ NumberForm[N[2/3], 30] stops after 15 to 16 decimals but does not round up. $\endgroup$
    – Titus
    Commented Nov 27, 2018 at 12:37

2 Answers 2

1
$\begingroup$
ClearAll[f]
f[x_, n_] := 
Module[{s = RealDigits[x, 10, n + IntegerLength@IntegerPart[x]]}, 
N[FromDigits[s[[1]]]/10^(n), n + s[[2]]]];

f[2/3, 20]     

0.66666666666666666666

$\endgroup$
2
$\begingroup$

Trunc[x_, n_] := N[FromDigits[RealDigits[x, 10, n]], n] also works.

$\endgroup$
1
  • $\begingroup$ Nice, I made a change in my code so that you always get n decimal digits like f[5000/3, 20]=1666.66666666666666666666. thanx for accepting $\endgroup$
    – ZaMoC
    Commented Nov 27, 2018 at 12:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.