• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

XF 2.0 Entity returns decimal as string

Jake B.

Well-known member
#1
I have a decimal(20,2) MySQL column called 'goal' and have this registered in my Entity as a FLOAT:

PHP:
'goal' => [
    'type' => self::FLOAT,
    'default' => 0,
],
However, when I try to use $campaign.goal somewhere it behaves as a string instead of a float. I don't think I did something wrong, but that's entirely possible as well
 

Chris D

XenForo developer
Staff member
#2
Yeah it's not what we'd expect to happen. The code in the ValueFormatter should cast this to be a float in all cases, even avoiding cases where it could instead be cast to an integer.

So I don't know if this is down to how the value is being used, or what the specific issue is?
 

Jake B.

Well-known member
#3
I'm just doing an \XF::dump on $campaign->goal and it's showing up as a string. I'm trying to use
PHP:
if (!$campaign->goal) {
     return false;
}
somewhere as well, and that isn't working because PHP doesn't handle "0.00" as false, but if I do

PHP:
    if (!(float) $this->goal) {
        return false;
    }
So something odd is definitely going on, I don't have any getters that would be overwriting the output, and if I do {{ dump($campaign) }} {{ dump($campaign.goal) }} it shows the following:

Screen Shot 2017-10-16 at 3.33.09 PM.png

So it's almost certainly handling all of my float columns as strings for one reason or another

These are stored in the database as decimal, not float. But I don't think that should make a difference here
 

Mike

XenForo developer
Staff member
#4
Generally speaking, value formatters aren't used for simple scalar types.

The thing is, float and MySQL's decimal aren't the same thing. Decimal is a fixed format that avoids the imprecision issues of floats and doubles. PHP doesn't have any fixed decimal formats so a string is the only way to truly ensure that the value isn't corrupted.
 

Jake B.

Well-known member
#5
Generally speaking, value formatters aren't used for simple scalar types.

The thing is, float and MySQL's decimal aren't the same thing. Decimal is a fixed format that avoids the imprecision issues of floats and doubles. PHP doesn't have any fixed decimal formats so a string is the only way to truly ensure that the value isn't corrupted.
I guess I'll just convert it to use floats, just not really not a fan of how they behave when dealing with currencies