Bash Decimal Calculations in Scripts

For discussions about programming, programming questions/advice, and projects that don't really have anything to do with Puppy.
Post Reply
Message
Author
slavvo67
Posts: 1610
Joined: Sat 13 Oct 2012, 02:07
Location: The other Mr. 305

Bash Decimal Calculations in Scripts

#1 Post by slavvo67 »

I am working on a project which includes using numbers with decimals. The small script below seems to work okay but I'm interested in any comments on this. Some Linux websites came up with other resolves that don't seem to work with the Bash included in Puppy.

1) Is there anything wrong with what I'm using below?

2) Are there easier ways or more proper ways to get the answer?

3) Would the script below fail under other mathematical circumstances (for example, multiplying, longer decimals, etc.)

#!/bin/bash

discount1=".0025"
discount2=".0050"
answer1=`echo "$discount1 + $discount2"|bc`
echo $answer1

Thanks for your comments.

Slavvo67

musher0
Posts: 14629
Joined: Mon 05 Jan 2009, 00:54
Location: Gatineau (Qc), Canada

#2 Post by musher0 »

Hi, slavvo67.

No, nothing wrong with your template, I just tried it.

bc will do all operations with decimals. expr will not. I have some experience
calculating with awk, and awk is pretty good at this, even if its syntax appears
sometimes counter-intuitive.

A starting point on awk and calculations could be :
-- https://ixquick.com/do/search?q=calculations+with+awk --

BFN.

musher0
musher0
~~~~~~~~~~
"You want it darker? We kill the flame." (L. Cohen)

slavvo67
Posts: 1610
Joined: Sat 13 Oct 2012, 02:07
Location: The other Mr. 305

#3 Post by slavvo67 »

Hi Musher0:

Thank you for the input and suggestion. I was looking at Awk for this, as well but it didn't seem to operate correctly in Bash. Not sure...

Thanks again,

Slavvo67

User avatar
Karl Godt
Posts: 4199
Joined: Sun 20 Jun 2010, 13:52
Location: Kiel,Germany

bc -l

#4 Post by Karl Godt »

Sometimes , I don't know why , but suspect a patch by distributions ,

bc needs the -l option :

-l, --mathlib
Define the standard math library.

Code: Select all

answer1=`echo "$discount1 + $discount2"|bc -l` 
Code that may work on one distro without the -l option; may need
the -l option in another distro .
«Give me GUI or Death» -- I give you [[Xx]term[inal]] [[Cc]on[s][ole]] .
Macpup user since 2010 on full installations.
People who want problems with Puppy boot frugal :P

slavvo67
Posts: 1610
Joined: Sat 13 Oct 2012, 02:07
Location: The other Mr. 305

#5 Post by slavvo67 »

Hi Karl,

Very interesting. Do you know if the -l option can be used by default in all version? So, no harm if hard-coded into a script?

Thanks again,

Slavvo67

amigo
Posts: 2629
Joined: Mon 02 Apr 2007, 06:52

#6 Post by amigo »

Passing an unknown option to most tools will return an error. You'd have to test for it and the n only invoke it if available. Messy, but so would checking the shell name(type) and version.

Post Reply