# Truncate a number in mathematica

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.

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

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

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

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