Tuesday, May 7, 2024
 Popular · Latest · Hot · Upcoming
37
rated 0 times [  37] [ 0]  / answers: 1 / hits: 164922  / 2 Years ago, sat, october 29, 2022, 2:52:40

A quick example of what I want using bash scripting:



#!/bin/bash
echo "Insert the price you want to calculate:"
read float
echo "This is the price without taxes:"
echo "scale=2; $float/1.18" |bc -l
read -p "Press any key to continue..."
bash scriptname.sh


Assuming that the price is: 48.86
The answer will be:41.406779661 (41.40 actually because I'm using scale=2;)



My Question is:
How I round the second decimal to show the answer in this way?: 41.41


More From » bash

 Answers
5

A bash round function:



round()
{
echo $(printf %.$2f $(echo "scale=$2;(((10^$2)*$1)+0.5)/(10^$2)" | bc))
};


Used in your code example:



#!/bin/bash
# the function "round()" was taken from
# http://stempell.com/2009/08/rechnen-in-bash/

# the round function:
round()
{
echo $(printf %.$2f $(echo "scale=$2;(((10^$2)*$1)+0.5)/(10^$2)" | bc))
};

echo "Insert the price you want to calculate:"
read float
echo "This is the price without taxes:"
#echo "scale=2; $float/1.18" |bc -l
echo $(round $float/1.18 2);
read -p "Press any key to continue..."


Good luck :o)


[#35962] Monday, October 31, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ditery

Total Points: 9
Total Questions: 116
Total Answers: 119

Location: Grenada
Member since Sun, Dec 20, 2020
3 Years ago
ditery questions
;