Search code examples
bashparameter-expansion

Separating integer and fractional part of a decimal number


I want to separate a numeric decimal number, storing the integer part in bash variable ts and the fractional part in variable fr.

Had a go with parameter expansion, but keep getting the original number.

t=13.491675 
ts=${t#![0-9]*}
fr=${t%*![0-9]}

Solution

  • This should work with any decimal separator:

    shopt -s extglob
    t=13.491675
    ts="${t%%[^0-9]+([0-9])}"
    fr="${t##+([0-9])[^0-9]}"