3

I saw this post, but I was wondering if there is a simpler command to round decimal numbers.

I have a file with milions of numbers:

0.1
1.2
3.8

I want to round them to integer

0
1
4

Is there a simple command to do that?

2 Answers 2

4

You can use the following perl oneliner:

perl -i -pe 's/(\d*\.\d*)/int($1+0.5)/ge' file

The -i option will automatically change your decimal numbers in-place.

The regex \d*\.\d* will ensure that only such numbers will be changed in your original file (i.e other strings will be left untouched)

1
  • This answer is more elegant, can handle lines with multiple numbers.
    – Hugolpz
    Jan 12, 2020 at 19:22
3

With the awk commands in the link you post, you'd get something like this:

awk '{printf("%d\n",$0+0.5)}' file

Or simpler, use:

awk '{printf("%.f\n",$0)}' file

I can come up with nothing easier than that ;)

2
  • 1
    I can: awk '{printf("%d\n",$1 + 0.5)}' filename ;-)
    – Jos
    Mar 25, 2015 at 15:30
  • Good point, I see @Kasiya has already added it for me ;)
    – MrHug
    Mar 25, 2015 at 20:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .