Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get bc(1) to print the leading zero?

Tags:

bash

unix

bc

I do something like the following in a Makefile:

echo "0.1 + 0.1" | bc 

(in the real file the numbers are dynamic, of course)

It prints .2 but I want it to print 0.2.

I would like to do this without resorting to sed but I can't seem to find how to get bc to print the zero. Or is bc just not able to do this?

like image 948
rwos Avatar asked Dec 06 '11 15:12

rwos


People also ask

What does a leading zero look like?

A leading zero is any 0 digit that comes before the first nonzero digit in a number string in positional notation. For example, James Bond's famous identifier, 007, has two leading zeros. When leading zeros occupy the most significant digits of an integer, they could be left blank or omitted for the same numeric value.

What does it mean to add leading zeros?

This means that when you make 1 as 001, Excel treats the new result as text with three characters (just like abc or xyz). Here is how to add leading zeroes using the TEXT function: If you have the numbers in column A (say from A2:A100), then select B2:B100 and enter the following formula: =TEXT(A2,”00000″)


2 Answers

You can also resort to awk to format:

 echo "0.1 + 0.1" | bc | awk '{printf "%f", $0}' 

or with awk itself doing the math:

 echo "0.1 0.1" | awk '{printf "%f", $1 + $2}' 
like image 103
Elias Dorneles Avatar answered Sep 20 '22 20:09

Elias Dorneles


This might work for you:

echo "x=0.1 + 0.1; if(x<1) print 0; x" | bc 
like image 43
potong Avatar answered Sep 18 '22 20:09

potong