0

I am currently trying to input prices into a .txt file.

So i want it when the user input:1.1

Instead of 1.1, I want it to become 1.10 instead. As it would look better for the table I am trying to make in the future. I would also like to round up or down if it goes more than 3 decimal places. (Thanks john1024 for the correction)

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232

1 Answers1

1

To read in a price and coerce it to have 2 decimal places, try:

IFS= read -rp "Enter the price: " var
printf -v var %.2f "$var"

The %.2f format tells printf to use two-decimal digits.

Examples:

$ IFS= read -rp "Enter the price: " var; printf -v var %.2f "$var"; echo "var=$var"
Enter the price: 1.2
var=1.20
$ IFS= read -rp "Enter the price: " var; printf -v var %.2f "$var"; echo "var=$var"
Enter the price: 1.123
var=1.12

Note: Bash's printf builtin can format numbers with decimal points but its arithmetic expressions cannot handle floating point numbers. For that, you will need more advanced shells such as ksh93, zsh or yash or tools like awk or bc.

John1024
  • 74,655