1

I saw this SO answer showing how you can remove all text after a character in a string in Bash. With this information, I can do something like this to round down a number:

NUMBER=10.12345
NUMBER=${NUMBER%.*} # 10

However, I want to keep two digits after the decimal. How can I get 10.12345 to be 10.12? I don't need to properly round, just trim. Perhaps something with wildcards when running ${NUMBER%.*}?

2 Answers 2

7

You can round a float with printf. Try printf "%.2f" "${NUMBER}". You could save the value into a variable as well: printf -v myvar "%.2f" "${NUMBER}".

1
  • Oh that's convenient. Thank you, I'll mark it as correct after the 10 minute timer is up Commented May 4, 2019 at 21:46
1

Using =~ operator:

$ num=10.12345
$ [[ $num =~ ^[0-9]*(.[0-9]{1,2})? ]] && echo $BASH_REMATCH
10.12
$ num=10
$ [[ $num =~ ^[0-9]*(.[0-9]{1,2})? ]] && echo $BASH_REMATCH
10

Not the answer you're looking for? Browse other questions tagged or ask your own question.