1825803 Members
2765 Online
109687 Solutions
New Discussion

Decimal add in ksh

 
SOLVED
Go to solution
Marcelo De Florio_1
Frequent Advisor

Decimal add in ksh

I need a summary this:
let TOTAL=$(($TOTAL + $CPU))

and then; TOTAL variable return integer result whitout decimal.

any ideas ?
Marcelo De Florio
6 REPLIES 6
A. Clay Stephenson
Acclaimed Contributor

Re: Decimal add in ksh

Hi Marcelo:

How about something like this:

#!/usr/bin/ksh

trunc()
{
printf "%.0f\n" $1
return 0
}

A=12.56
B=4.2

echo "A=${A}"
echo "B=${B}"

A=`trunc ${A}`
B=`trunc ${B}`

TOT=$((${A} + ${B}))
echo "TOT = ${TOT}"

exit 0

Clay
If it ain't broke, I can fix that.
James R. Ferguson
Acclaimed Contributor
Solution

Re: Decimal add in ksh

Hi Marcelo:

One way is:

# TOTAL=17.11
# CPU=0.37

# TOTAL=`$TOTAL $CPU|awk '{print $1 + $2}'`
# echo $TOTAL

Another is:

# TOTAL=`echo "scale=2;$TOTAL + $CPU"|bc`
# echo $TOTAL

...JRF...
Marcelo De Florio_1
Frequent Advisor

Re: Decimal add in ksh

Clay, I need a view result

A + B=16.76

How can i view this result?

regards
MDF
Marcelo De Florio
James R. Ferguson
Acclaimed Contributor

Re: Decimal add in ksh

Hi (again) Marcelo:

Sorry, in the first example, I forgot the 'echo'. It should read:

# TOTAL=`echo $TOTAL $CPU|awk '{print $1 + $2}'`

...JRF...
A. Clay Stephenson
Acclaimed Contributor

Re: Decimal add in ksh

Sorry Marcelo, I read your question to mean that you had floating point operands that you wanted to convert to an integer total.

A=12.56
B=4.67

TOT=`echo "${A} ${B}" | awk '{printf("%.2f\n",$1,$2)}'`

That should do the floating point total rounded to 2 decimal places. You can change the printf format to any desired precision.

Clay

Clay
If it ain't broke, I can fix that.
Sundar_7
Honored Contributor

Re: Decimal add in ksh

Hi,

U can try this

TOTAL = `echo "$TOTAL + $CPU" | bc -l `

This should return TOTAL in Decimal

Sundar
Learn What to do ,How to do and more importantly When to do ?