[SOLVED] Adding one or two decimal places in an amount

Anything beyond the basics in using the LiveCode language. Share your handlers, functions and magic here.

Moderators: heatherlaine, Klaus, FourthWorld, robinmiller, kevinmiller

Post Reply
karmacomposer
Posts: 256
Joined: Wed Apr 27, 2011 2:12 pm

[SOLVED] Adding one or two decimal places in an amount

Post by karmacomposer » Mon Jul 23, 2018 10:53 pm

Say I have an amount of money that is automatically calculated and then rounded.

It either ends in 55.5 or 55

I need it to be 55.50 or 55.00

How do I append the decimal places and have it figure out whether it needs one 0 or two 0's at the end?

Thanks

Mike
Last edited by karmacomposer on Tue Jul 24, 2018 3:52 pm, edited 1 time in total.

Klaus
Posts: 10386
Joined: Sat Apr 08, 2006 8:41 am
Location: Germany
Contact:

Re: Adding one or two decimal places in an amount

Post by Klaus » Mon Jul 23, 2018 11:31 pm

Hi Mike,

I always use the FORMAT() function for this:

Code: Select all

...
put your_result_of_computing_numbers into tNumber
put format("%1.2f",tNumber) into tNumberWith2DecimalPlaces
## This will force two decimal places of the supplied number
...
Best

Klaus

dunbarx
VIP Livecode Opensource Backer
VIP Livecode Opensource Backer
Posts: 5569
Joined: Wed May 06, 2009 2:28 pm
Location: New York, NY

Re: Adding one or two decimal places in an amount

Post by dunbarx » Mon Jul 23, 2018 11:40 pm

What Klaus said.

It may also be useful to know about the "numberFormat" property. Though it is a bit old fashioned, it may be easier to grok. Again, see the dictionary.

Try this in a button script;

Code: Select all

on mouseUp
   set the numberFormat to "#.00"
     answer 55 + 0
   answer  55.5 + 0
   answer 55.55 + 0
   
   put "55.5" into temp
   answer temp
end mouseUp
The extra bit about adding "0" is because the property only acts upon an arithmetical operation, not on an existing string. In general, the property is set, and then all subsequent arithmetic operations are covered. But you see that the last line does not conform to what you might want.

using "format", you would have to:

Code: Select all

 answer  format("%1.2f","55.5") 
So you need to "use" the function each time you need it. The "numberFormat" property can be set sort of "globally" within a handler.

Craig Newman

karmacomposer
Posts: 256
Joined: Wed Apr 27, 2011 2:12 pm

Re: Adding one or two decimal places in an amount

Post by karmacomposer » Tue Jul 24, 2018 3:52 pm

Thank you Klaus. That worked perfectly.

Mike

Post Reply

Return to “Talking LiveCode”