Search code examples
stringbashtrim

Bash - Remove all text after characters using wildcards


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%.*}?


Solution

  • 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}".