← Back to Bash Course | Chapter 4: Loops | Lesson 7 of 14

Floating-Point Math के लिए bc

Bash सिर्फ whole numbers count कर सकता है, एक kid की तरह जो सिर्फ apples जानता है, half apples नहीं। bc वह friend है जो decimals समझता है, इसलिए आप sum उसे hand कर देते हैं।
Syntax
bash
result=$(echo "expression" | bc -l)

bc for Floating-Point Math

Bash arithmetic सिर्फ integers handle करता है, इसलिए bc (basic calculator) उपयोग होता है जब आपको decimal precision चाहिए।

आप आमतौर पर एक expression string इसमें pipe करते हैं, जैसे echo "10 / 3" | bc -l, जहां -l ज़्यादा precision वाली एक math library load करता है। यह shell scripts में floating-point calculations के लिए standard workaround है।

Note: Decimal results चाहिए, सिर्फ truncated integers नहीं, तो हमेशा plain bc के बजाय bc -l उपयोग करें।

उदाहरण: bc for Floating-Point Math

bash
#!/bin/bash
result=$(echo "10 / 3" | bc -l)
echo "10 / 3 = $result"

result=$(echo "scale=2; 22/7" | bc -l)
echo "22 / 7 (2 decimal places) = $result"
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. Decimals के लिए $(( )) उपयोग करना, जो integers में truncate हो जाता है।
  2. scale= भूल जाना, इसलिए echo "10/3" | bc 3 print करता है।
  3. bc install करना भूल जाना, जो हर minimal system पर मौजूद नहीं होता।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.