Is there a simpler way to validate user input for float?

I'm trying to only read price (FLOAT (i.e 1.10, 3.14, etc etc))
If the input is just an integer, I will add a .00 behind. (i.e 3 becomes 3.00 , 20 becomes 20.00)
If the input is without 2 decimal places, I'll add a 0. (i.e 3.1 becomes 3.10)
I tried using the below code, it works but I don't think this is the right way to do it since I'm gonna have never ending elif statements for different conditions.
Am I doing it wrongly?
Thanks in advance.

if [[ $price =~ [^0-9.] ]] ; then 
echo "Error"
 
else
 
if [[ $price == [.][0-9] ]] ; then
price="0""$price""0"
elif [[ $price == [.][0-9][0-9] ]] ; then
price="0""$price"
elif [[ $price == [0-9] ]] ; then
price="$price.00"
elif [[ $price == [0-9][.] ]] ; then
price="$price""00"
elif [[ $price == [0-9][0-9] ]] ; then
price="$price.00"
elif [[ $price == [0-9][0-9][.] ]] ; then
price="$price""00"
elif [[ $price == [0-9][0-9][.][0-9] ]] ; then
price="$price""0"
fi
 
fi

Use printf:

price=$(printf "%0.2f" $price)

Thanks , but can you kindly explain what this code does?
Rarely used printf.

a) Using the bc function. That is the calculator function built-in to most unix flavors. I will have to ponder this a bit.
b) Use awk and printf to adjust.
c) You are really only concerned with three situations - two decimals, one decimal, no decimal. If you go that route, use wildcards for numbers to the left of the decimal point.

# x="sed '/[0-9][0-9]*\.*[0-9]*/s/\(.*\)\.\(.\)$/\1.\20/;/^[0-9][0-9]*$/s/\(.*\)/\1.00/'"
# a=12 ; echo $a|eval $x
12.00
# a=12.1 ; echo $a|eval $x
12.10
printf "%0.2f" $price

Prints a value in 2 decimal places.

1 Like

ksh93

typeset -F2 price
price=100
echo $price