Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

'Bug' with formatted printing ?

Status
Not open for further replies.

DiscoPants

Programmer
Apr 9, 2003
3
GB
Hello, I wonder if anybody can help? Below is a simple command to print a mathematical equation giving the correct return:-
> echo "a" | awk '{ print(70.57 * 100) }'
7057

If I try and format this using a decimal integer I get the wrong return:-
echo "a" | awk '{ printf("%d\n", 70.57 * 100) }'
7056

Is this a bug or is there someting I blatantly missing and should quit computers?
 

The problem here is that 70.57 * 100 is not exactly equal to 7057 because of rounding errors. You can see this with the following program:

awk 'BEGIN{ printf("%20.16f\n", 70.57 * 100);exit }

which produced

7056.9999999999991000

One way around the problem in this case is to use

awk 'BEGIN{ printf("%.0f\n", 70.57 * 100);exit }

which rounds rather than truncates the argument. CaKiwi

"I love mankind, it's people I can't stand" - Linus Van Pelt
 
Cheers mate, I'd decided to use a floating number too.

Just can't understand why multiplying a number with 2dp by 100 can go wrong!

Cheers!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top