Bash: How to Round Numbers to 2 Decimal Places


Often you may want to round numbers to exactly two decimal places in Bash.

You can use the printf command with the following syntax to do so:

printf %.2f "$val"

This particular example prints the number stored in the variable named $val rounded to exactly two decimal places.

Note: To round a number to a different number of decimal places, simply change the 2 to a different number. For example, you can use %.3f to instead round to 3 decimal places.

The following example shows how to use this syntax in practice.

Example: How to Round Numbers to 2 Decimal Places in Bash

Suppose we create a variable in Bash named $val that contains the value 12.4388.

We can use the following syntax to round this number to 2 decimal places:

val=12.4388
printf %.2f "$val"

The following screenshot shows how to use this syntax in practice:

Bash round number to 2 decimal places

Notice that our original value of 12.4388 has been rounded to 12.44.

It’s also worth noting that if you use the printf command to round numbers that don’t contain at least two decimal places then two decimal places will be displayed by default.

For example, suppose we create a variable that contains the number 12 instead:

Notice that our original value of 12 is shown as 12.00.

Keep this in mind when using the printf command to round numbers to a specific number of decimals.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Calculate the Average of a Column
Bash: How to Slice an Array
Bash: How to Append Values to Array

Leave a Reply