Printing to two decimal places.

SYS 64738
User avatar
Shaun_B
Member
Member
Posts: 179
Joined: Tue May 06, 2014 12:12 pm
Location: UK
Contact:

Printing to two decimal places.

Post by Shaun_B »

I was trying to work out a way of printing a number to two decimal places, like:

Code: Select all

// 33.49 plus VAT would be:
printf("%.2f", 33.49 * 1.2);
would in C. I'm sure there's a better method, but this seems to work:

Code: Select all

10 def fn u(a) = int(a)+(int(100*(a-int(a)))/100)
20 def fn r(a) = a+2^-24
30 input "please enter a floating point number";a
40 a = fn u( fn r(a) )
50 print "to two decimal places, it's:"a;
60 if a = fn r(int(a)) or a = int(a) then print"{left}.00"
70 for i=10 to 90 step 10
80 if fn u( fn r(a-int(a)) ) = fn u( fn r(i/100) ) then print "{left}0"
90 next i
100 poke 198,0:wait 198,1
The function in line 10 returns the number as either a whole number, or to one or two decimal places.

The function in line 20 seems to help in eliminating rounding errors.

Obviously I haven't tested all real numbers and it truncates rather than rounds up to the nearest penny (for instance). Does anyone know of a better method?

Edit: typo alert, n * 1.8 would not give you price + VAT as VAT is not 80% - corrected.

Regards,

Shaun.


BASIC Programming - making the mistakes so that you don't have to.
Circles and Squares.
Nothing I post here will stand up in a court of law.
ajordison
Developer
Developer
Posts: 59
Joined: Wed Apr 16, 2014 1:28 pm
Location: Hartlepool, UK
Contact:

Re: Printing to two decimal places.

Post by ajordison »

This method truncates too and is not as maths intensive, but I can't say if it's quicker or not:

Code: Select all

10 input n
20 rem make sure the number has a decimal point in it
30 n=n+0.00001
40 rem turn it into a string
50 v$=str$(n)
60 rem find the decimal point
70 for i=1 to len(v$):if mid$(v$,i,1)= "." then goto 100
80 next i
90 rem truncate the string two chars after the decimal point
100 print left$(v$,i+2)
110 end
Try out CBM prg Studio for all your Commodore development needs!
Stay a while...stay for erm quite a while!
User avatar
Shaun_B
Member
Member
Posts: 179
Joined: Tue May 06, 2014 12:12 pm
Location: UK
Contact:

Re: Printing to two decimal places.

Post by Shaun_B »

I didn't think of approaching the problem that way. It's obvious that my maths is quite weak so I try to solve problems using as much maths as possible, but this is certainly a lot neater.

Thanks,

Shaun.
BASIC Programming - making the mistakes so that you don't have to.
Circles and Squares.
Nothing I post here will stand up in a court of law.
Post Reply Previous topicNext topic

Who is online

Users browsing this forum: No registered users and 6 guests