How to do calculations in Mac Terminal


If you are wondering which command line utility to use on your Mac Terminal to do arithmetic calculations such as addition, subtraction or multiplication then you can make use of bc - An arbitrary precision calculator language, it ships with your macOS.

Math Calculations on Mac Terminal
Math Calculations on Mac Terminal
% man bc

bc(1)                                                                    bc(1)

NAME
       bc - An arbitrary precision calculator language

SYNTAX
       bc [ -hlwsqv ] [long-options] [  file ... ]

VERSION
       This man page documents GNU bc version 1.06.

DESCRIPTION
       bc  is a language that supports arbitrary precision numbers with inter-
       active execution of statements.  There are  some  similarities  in  the
       syntax  to  the  C  programming  language.   A standard math library is
       available by command line option.  If requested, the  math  library  is
       defined before processing any files.  bc starts by processing code from
       all the files listed on the command line in the  order  listed.   After
       all  files  have been processed, bc reads from the standard input.  All
       code is executed as it is read.  (If a file contains a command to  halt
       the processor, bc will never read from the standard input.)

Lets see some examples:

code2care@mac ~ % bc
bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 

20+10+30
60


a=10
b=20

a+b
30


(a+b)*100
3000


(10/20)*100
0

You can see that the division came out to be incorrect, that because the result is truncated to an integer, you would need to use the -l option to work with floats.

-l, --mathlib

Define the standard math library

code2care@mac ~ % bc -l
bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 


(10/20)*100
50.00000000000000000000



Recent Posts:




Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and Software Developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include Learnings, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.