Calc element stop rounding

nycreate

Member
Hi All,
This is prob an easy one for everyone even a slight bit more intelligent than me!

I have a calc element with the calculation

return (int)'{table___weight}'-'{table___weight_nok}';

table___weight & table___weight_nok are set as decimal fields.

how do I stop the calculation rounding up? & show accurate number?

ie it gives 22.5 - 3.2 = 18.8? (should be 19.3)

on another calc element i have

return (int)('{table___weight}'-'{table___weight_nok}')*0.60;

which would give (22.5 - 3.2) x 0.6 = 11.4 (should be 11.58 )

Thanks in advance.
 
Well, it's doing exactly what you asked it to do. :)

You are casting table_weight to an int. Int is integer. Whole numbers. So casting (int)'22.5' gives you 22.

If your numbers are fractional, i.e. have decimal points, then cast to (float) ... oh, and remember to cast all of them:

PHP:
return (float)'{table___weight}' - (float)'{table___weight_nok}';

... and ...

PHP:
return ((float)'{table___weight}' - (float)'{table___weight_nok}') * 0.60;

-- hugh
 
Just a quick one on this....
how do I format the answer to 2 dec places? ie I want to keep the '0' at end. if the answer is say 15.35 is shows this ok but if its 15.30 it shows as 15.3.

Thanks in advance.
 
Did you try typing that question into google, like "how do i format a number to two decimal places in php"? It's not really a Fabrik question, just a generic PHP question, and you'll find Mr Google has lots of helpful suggestions.

Anyway ... there's a few ways. Easiest is number_format(), which also allows for thousand separators, like 1,234.50., and international formats like 1.234,50 Most configurable is sprintf(), but that requires a little understanding sprintf() format strings.

So, with number_format ...

http://php.net/number_format

PHP:
return number_format((float)'{table___weight}' - (float)'{table___weight_nok}', 2);

See the PHP doc if you want to add sepchars, etc.

Also note that number_format() does "half round up", meaning a 5 gets rounded up:

1.234 becomes 1.23
1.235 becomes 1.24

If you need half rounding down, just google it. There's several ways round it.

-- hugh
 
Hi Hugh,
Yes I ALWAYS troll the forum and google before I ask questions so I try my best not to waste your time, (I even use LMGTFY for my clients) but after faffing trying to work things out unsuccessfully and given your previous excellent help with custom components and scripts I thought this might be a simple question for a man of your calibre! ;-)

Thanks
 
We are in need of some funding.
More details.

Thank you.

Members online

Back
Top