"Joel C. Salomon" <(E-Mail Removed)> writes:

> On 02/08/2011 02:06 PM, Bill Cunningham wrote:

>> int price=2000;

>> now int is 2000

>> printf("%d\n",2000/10); ?

>>

>> To make 20 USD ?

>

> No, because the expression 2000/100 is an integer expression. It’ll

> give you the right answer here, but the wrong type. Worse, by rules of

> integer arithmetic, 2054/100 gives 20, not 20.54.

>

> Try

> printf("%f\n", price/100.0);

> instead. Dividing by an explicitly floating-point number yields a

> floating-point number, and the “%f” format is what’s needed then.

>

> (Then look up printf() format flags to learn how to print a number with

> exactly two digits past the decimal point.)
When dealing with money, it's probably best not to use floating-point

arithmetic at all.

(I think there are ways to used floating-point reliably for money,

but it requires very careful programming.)

For example, if you store the price as an integer number of cents,

price/100 gives you the whole number of dollars, and price%100

gives you the remaining number of cents:

printf("The price is $%d.%02d\n", price / 100, price % 100);

Note that Bill divided by 10, not by 100. The fact that this is a

very typical error for him suggests that Bill should not be writing

software that deals with money.

--

Keith Thompson (The_Other_Keith)

(E-Mail Removed) <http://www.ghoti.net/~kst>

Nokia

"We must do something. This is something. Therefore, we must do this."

-- Antony Jay and Jonathan Lynn, "Yes Minister"