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

APixel Visuals
  • 1,508
  • 4
  • 20
  • 38

2 Answers2

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

Tony Stark
  • 2,318
  • 1
  • 22
  • 41
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
James Brown
  • 36,089
  • 7
  • 43
  • 59