How do I calculate floating point numbers in shell?

Source: Internet
Author: User
Tags float number

It has the most basic mathematical computing capabilities in shell, such as expr and let. However, these operations can only process integer data. To calculate decimals, you must use the BC command extension. The following example shows how to determine the output parameter type and calculate its square.

  1. #! /Bin/sh
  2. # Filename: testbc
  3. Var = $1
  4. Dd = $ (echo $ var | BC 2>/dev/null)
  5. If ["$ Var "! = "$ Dd"] | ["$ Var" = ""]; then
  6. Echo "$ var isn't number! "
  7. Elif echo $ var | grep "/.">/dev/null 2>
  8. Then
  9. # Square = $ (echo "$ Var * $ Var" | BC)
  10. Square = $ (echo "$ Var * $ Var" | BC-l)
  11. Echo "$ VaR is a float number, square is: $ square"
  12. Else
  13. Square = $ (echo "$ Var * $ Var" | BC)
  14. Echo "$ VaR is a int number, square is: $ square"
  15. Fi

The script execution result is as follows:

$ Testbc aaa

AAA isn' t number!

$ Testbc 2

2 is a int number, square is: 4

$ Testbc 1.5

1.5 is a float number, square is: 2.25

 

If you want to process the accuracy of the calculation result, you can use scale to define the accuracy. You can do this:

$ Echo "scale = 3; 1.55*1.55" | BC-l

2.402

If the precision is not defined, the value of 1.55*1.55 is: 2.4025. Because we define the precision as 3, it displays the last three decimal places.

$ Echo "1.55*1.55" | BC-l

2.4025

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.