A short one today. Bash can only handle integer numbers and not floats, so when someone searches the internet on how to use math on floats in bash the solution they find is usually “use bc” and looks something like this:
1 2 3 | $ f=12.3456 $ bc -l <<< "${f} * 10" 123.4560 |
Or if they want the result to be an integer:
1 2 3 | $ f=12.3456 $ bc -l <<< "scale=0; ${f} * 10 /1" 123 |
It’s a fine solution, and readable (which can mean a lot for people maintaining scripts). But if all you want to do is multiply by 10,100,1000, … you can achieve this faster with a bit of string manipulation:
1 2 3 | $ f=12.3456 $ _sub="${f#*.}" $ echo "${f%.*}${_sub:0:1}.${_sub:1}" |
It just splits the number into two strings, and assembles it again with the decimal shifted. Have a look at substring_removal and substring_expansion for more examples on how to modify strings in bash. I’d highly suggest either sticking this in a separate function, or commenting the code since it isn’t necessarily obvious what is going on
Since it is all pure bash and doesn’t need to spawn external commands, it quicker (not that bc is slow, but if you are doing a lot of calculations, it can add up). I know what you are thinking “if your goal is speed, you shouldn’t be using bash”, that doesn’t mean we can’t write efficient code.