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.

有帮助吗?

解决方案

In bc:

bc <<EOF
scale = $precision
$value / (10 ^ $precision)
EOF

In sed:

sed -e "s/[0-9]\{$precision\}$/.&/" <<< "$value"

其他提示

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}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top