Rounding floats to ints with bc in bash

I’ve seen a lot of bizarre attempts to round floating point numbers to integers in bash. Here’s my cheap hack using bc:


echo "($float+0.5)/1" | bc

If your floating point number is in a variable called float then this will round up or down accordingly. As in 1.0 and 1.4 round to 1, while 1.5 and 1.9 round to 2.

Tags: , , , , , ,

4 Responses to “Rounding floats to ints with bc in bash”

  1. piponazo says:

    The best trick to round float values I’ve ever been ;)

  2. piponazo says:

    Althought in bash scripts you can simply put this:

    #!/bin/bash
    printf %0.f 5.6

    and obtain the closest integer to the especified value. However, if you try to run the printf command from a terminal the number is not recognized (at least with my keyboard configuration)

  3. [...] http://www.alecjacobson.com/weblog/?p=256 GD Star Ratingloading… Categories: Programación, Scripting, Terminal Tags: awk, bash, bc, echo, float, redondear, Script, Terminal Comentarios (0) Referencias (0) Dejar un comentario Referencia [...]

  4. ajx says:

    Cool! It works on my terminal. I added a little \\n for a new line:

    
    printf %0.f\\n 5.6
    
    

Leave a Reply