1
$\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$
  • $\begingroup$ just try N[2/3, 20] $\endgroup$ – J42161217 Nov 27 '18 at 12:10
  • $\begingroup$ N rounds the last decimal digit. I get N[2/3, 20] = 0.66666666666666666667 $\endgroup$ – Alex Spanos Nov 27 '18 at 12:12
  • 1
    $\begingroup$ You probably want to use RealDigits[2/3, 10, 20] $\endgroup$ – Carl Lange Nov 27 '18 at 12:18
  • $\begingroup$ NumberForm[N[2/3], 30] stops after 15 to 16 decimals but does not round up. $\endgroup$ – Titus Nov 27 '18 at 12:37
0
$\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$
0
$\begingroup$

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

$\endgroup$
  • $\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$ – J42161217 Nov 27 '18 at 12:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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