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
  • 55,929
  • 26
  • 146
  • 227
pandora
  • 3
  • 6

1 Answers1

0

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

read -p "Enter the price: " var
printf -v var '%.2f' "$var"

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

Examples:

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

Note: Bash can format numbers with decimal points but it cannot do addition, subtraction, or other arithmetic on such floating point numbers. For that, you will need other tools like awk or bc or zsh.

John1024
  • 73,527
  • 11
  • 167
  • 163