Page 1 of 1

Using "format()" to create decimal place.

Posted: Tue Nov 22, 2022 6:01 am
by Googie85
Hi Guys!!

I am trying to use the following code to add a ".00" after a given number.

Code: Select all

put 10 into temp
add 10 to temp
format(temp,".00")
answer temp
I need some help to get this to work. All replies greatly received!

Thanks,

Googie.

Re: Using "format()" to create decimal place.

Posted: Tue Nov 22, 2022 8:23 am
by SparkOut
Try
format("%.2f",temp)

The first argument is the template to be used (in quotes) with % as the wildcard for whatever numbers, then a decimal point and then 2 significant figures of a floating point version of the calculated result.

The result is returned as a string representation of the number that you formatted.

There are lots of different formatting templates to use.

Re: Using "format()" to create decimal place.

Posted: Tue Nov 22, 2022 1:11 pm
by richmond62
What is unclear to me is if:

1. You want all your numbers set to 2 decimal places,

or

2. You 'just' want to put ".00" after any whole number.

As LiveCode does not differentiate between numeric and text strings when in variables #2 is simply a matter of this:

Code: Select all

put ".00" after XXX
if it is #1 you want then try this, for example:

Code: Select all

on mouseUp
   put 123.45678 into XXX
   put the format("%1.2f", XXX) into XXX
   put XXX
end mouseUp

Re: Using "format()" to create decimal place.

Posted: Tue Nov 22, 2022 7:29 pm
by dunbarx
CAsba.

Although considered less modern that the "format" function, it is useful to read about the "numberFormat" property in the dictionary.

Craig

Re: Using "format()" to create decimal place.

Posted: Tue Nov 22, 2022 7:33 pm
by FourthWorld
Hi Googie85 -

There's also one other option which may fit will with your conceptualization of number formats: the numberFormat global property.

You can set that property to a formatting template, and then subsequent operations on a number will take on that formatting when displayed.

Using your example:

Code: Select all

put 10 into temp
set the numberFormat to "0.00"
add 10 to temp
answer temp
"0" is used in the numberFormat template string for padding zero values, and "#" can be used as a placeholder for non-zero values.

For details, see the Dictionary entry for numberFormat (under the Help menu, see the third item, "Dictionary (API)".