4

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.

1 Answer 1

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
2
  • 1
    This can be optimised, see answers (also stuffed with other CLI calculators): askubuntu.com/questions/378661/…
    – hc_dev
    Sep 18, 2020 at 22:24
  • 1
    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, 2020 at 19:54

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .