0

I work in a psych lab and am relatively new to R. I'm struggling to understand how trunc() works in the following example:

(1.125+.005)*100 # returns 113
trunc(113) # returns 113
trunc(113)/100 # returns 1.13
trunc((1.125+.005)*100)/100 # ...returns 1.12

On the final line, why does trunc() return 1.12 instead of 1.13? Very grateful for any help understanding this. Ultimately my goal is to 1) get a mean (here, 1.125) 2) add .005 (thus 1.13) 3) drop all digits after the second decimal place, without rounding (and get 1.13), hence trunc(x*100)/100.

Any help much appreciated!

r-n00b
  • 1
  • 5
    https://stackoverflow.com/q/9508518/7128934. `trunc` removes everything after decimal. On the final line, the value inside `trunc` is very close to but not quite 113 - `sprintf("%.15f", (1.125+.005)*100)`. So `trunc` keeps only 112. – d.b Mar 12 '20 at 03:25
  • Thank you! Your help enabled me to find what seems like a good solution: trunc(round((1.125+.005)*100, digits = 3))/100 – r-n00b Mar 12 '20 at 05:21

0 Answers0