Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

divide in bash to 1 decimal place

Status
Not open for further replies.

w5000

Technical User
Nov 24, 2010
223
PL
hello,

on a system having no bc, perl, awk, and to which I have no administrator rights (only common user account), with restricted shell (bash), sed and expr available, I need to be able divide numbers to 1 decimal place:

> echo $((10/10))
1
> echo $((5/10))
0

I'd like to get 1.0, 0.1, etc (so leading zero for <1)

also builtin let gives 0
> let "m=1/4";echo $m
0

thanks in advance for a hint!
 
bash doesn't have floating point maths built in, so without 'bc' and it's associated scale=n, decimal places simply are not going to happen.

try expr 4 / 3 and see what the result is.



Chris.

Indifference will be the downfall of mankind, but who cares?
Time flies like an arrow, however, fruit flies like a banana.
Webmaster Forum
 

so it looks there is no local solution on this host...

> expr 4 / 3
1

> expr 1 / 3
0
 
Hi

If you want to keep your script pure Bash, you can do a trick by multiplying the dividend enough so integer arithmetics give precise enough result, then add separate the fractional part with string operation :
Bash:
[navy]m[/navy][teal]=[/teal][navy]$(([/navy] [COLOR=#993399]4[/color] [teal]*[/teal] [COLOR=#993399]10[/color] [teal]/[/teal] [COLOR=#993399]3[/color] [navy]))[/navy]
echo [i][green]"${m:0:-1}.${m: -1}"[/green][/i]

But better use tool instead. Either the already mentioned Bc with its verbose syntax, or Dc :
Code:
[blue]master #[/blue] bc <<< 'scale=1;4/3'
1.3

[blue]master #[/blue] dc <<< '1k4 3/p'
1.3


Feherke.
feherke.ga
 
If it's for scale 1 why not simply multiply the numerator by 10 and use string manipuation to insert the point.
Maybe something like this (rough draft):
Code:
#!/bin/bash

X=3
Y=4

X10=$(($X*10))

R=$(($X10/$Y))
[ $(($X/$Y)) -ge 1 ] && RD=${R:0:${#R}-1}.${R:${#R}-1} || RD=0.$R

echo $RD
Just keep in mind that your result is a string...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top