I have a number stored in a shell variable called x=”240570.578″. I would like to print $x as 2,40,570.57. How do I replace the number with their currency format under bash shell scripts?

The echo statement can not be used to format numbers under bash / ksh shell. You need to use printf command to format and print data according to FORMAT.

Syntax

Tutorial details
Difficulty level Easy
Root privileges No
Requirements printf
Est. reading time N/A
The syntax is:

printf "%'.2f" var

OR

printf "%'.2d" var

OR

printf "Total Rs.%'.2f" var

OR

printf "Total $.%'.2f" var

The ' act as a field and printing modifiers for decimal conversions, the thousands grouping separator is applied to the integer portion of the output according to the current LC_NUMERIC. Run the locale program to check current settings for LC_NUMERIC:

locale

Sample outputs:

LANG=en_IN
LANGUAGE=en_IN:en
LC_CTYPE="en_IN"
LC_NUMERIC="en_IN"
LC_TIME="en_IN"
LC_COLLATE="en_IN"
LC_MONETARY="en_IN"
LC_MESSAGES="en_IN"
LC_PAPER="en_IN"
LC_NAME="en_IN"
LC_ADDRESS="en_IN"
LC_TELEPHONE="en_IN"
LC_MEASUREMENT="en_IN"
LC_IDENTIFICATION="en_IN"
LC_ALL=

I’ve setup LC_ALL and LANG as follows in bash. You need to put the following lines in your ~/.bashrc and/or ~/.profile files:

export LC_ALL=en_IN.UTF-8
export LANG=en_IN.UTF-8
export LANGUAGE=en_IN.UTF-8

Examples

Type the following commands:

x="240570.578"
printf "%'.2f\n" $x
printf "Total $%'.2f\n" $x
printf "Total INR.%'.2f\n" $x

Sample outputs:

2,40,570.58
Total $2,40,570.58
Total INR.2,40,570.58
Recommended readings

man printf
man 3 printf
man local


🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 3 comments so far... add one


CategoryList of Unix and Linux commands
Disk space analyzersdf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
3 comments… add one
  • Jalal Hajigholamali Nov 27, 2012 @ 6:49

    Hi,

    Thanks for reminding me power of bash

  • Philippe Petrinko Nov 27, 2012 @ 8:32

    Hi Vivek,

    Yes, [printf] may be one of the less known bash shell builtin command, good to give us a short and quick example.

    –P

  • ITN John Nov 27, 2012 @ 12:39

    Say $x

    x="The price for the old server is 1456.75 and for ten servers price will be 2057654.50"

    Now, how do you format x?

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum