Skip site navigation (1)Skip section navigation (2)
Date:      Mon, 12 Nov 2007 14:44:08 +0100 (CET)
From:      "Peter Boosten" <peter@boosten.org>
To:        "Patrick Dung" <patrick_dkt@yahoo.com.hk>
Cc:        FreeBSD Questions <freebsd-questions@freebsd.org>
Subject:   Re: question about floating point calcuation with shell script / bc
Message-ID:  <63041.212.159.200.167.1194875048.squirrel@www.boosten.org>

next in thread | raw e-mail | index | archive | help
On Mon, November 12, 2007 14:01, Patrick Dung wrote:
> Hi
>
>
> I have a file with numbers in each line.
> Each number is a decimal number.
> My task is to add them up and get the final answer.
>
>
> I have searched with the search engine.
> I found bash cannot handle floating point calculation.
>
>
> I tried to use 'bc' and found if the final answer is < 1 (eg. 0.2)
> It display .2 instead of 0.2 (no leading zero).
>
>
> Any suggestion or other methods?
> I know ksh could do floating point calculation
> but I am now familiar with ksh.
>

Try awk

awk '{sum +=3D $1} END {printf "%.2f\n", sum}' file

assuming the file consists only of numbers in the first column.

Peter


--=20
http://www.boosten.org





Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?63041.212.159.200.167.1194875048.squirrel>