1

I often want to copy/paste some numbers from a website into a calculator to do some quick arithmetic. These numbers are typically formatted for display, so they include commas as thousands separators (1,234,567 instead of 1234567).

I'd like a command line calculator that lets me do basic arithmetic and ignores the commas.

Tools considered:

  • bc: Does not support commas
  • python: Does support thousand separators, but they have to be 1_234_567 instead of 1,234,567.
  • Google: supports commas! But I'd prefer a command line tool to a search engine.

I'm on macOS.

0

Conversion, then pipe to bc

You could remove any commas before handing input to bc via command-line.

For example use sed, then | (speak "pipe") to bc

Just strip off the unwanted comma characters by a regex substitution:

$ echo '123,456.78 * 100' | sed 's/,//g' | bc

outputs

12345678

As executable script:

#!/bin/bash
echo 'Input bc expression (thousand-separator commas will be removed):'
read line
normalized=`echo -n "$line" | sed "s/,//g"`
echo "Following will be passed to bc: $normalized"
echo "$normalized" | bc
| improve this answer | |
  • This can be optimised, see answers (also stuffed with other CLI calculators): askubuntu.com/questions/378661/… – hc_dev Sep 18 at 22:24
  • Sure this works, but bc is an interactive calculator. Using it this way forces you to use it as a batch process, which isn't quite what I'm hoping for. – danvk Sep 20 at 19:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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