Convert (integer,precision) pair to a float in bash/bc
Question
I have two numbers, $value and $precision. I need to make a "floating-point" representation of these numbers (though of course the output will actually be a string, since this is bash).
$precision tells me how many decimal points the number should have.
Example:
$value=123, $precision=2
This should give the output "1.23".
How can I do this elegantly from Bash? I am looking at the "bc" man page but I'm not really seeing any way there. I assume the simplest way is to treat my input value as a string and insert the char '.' in the right position somehow.
La solution
In bc
:
bc <<EOF
scale = $precision
$value / (10 ^ $precision)
EOF
In sed
:
sed -e "s/[0-9]\{$precision\}$/.&/" <<< "$value"
Autres conseils
OK, so I found some string manipulation help for Bash ... This does the trick, but it is hardly pretty. Posting it here for posterity.
lastIndex=$((${#value}-1))
dotIndex=$((${#value}-$precision))
decvalue=${value:0:$dotIndex}.${value:$dotIndex:$lastIndex}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow