Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to type decimal in PHP?

Tags:

php

php-7

I keep a field in the database that has a decimal type.

How can I type this?

public function getPrice() : decimal
{
    $temp = 123.45;
    return $temp;
}

It is not working, because return:

Fatal error: Uncaught TypeError: Return value of getPrice() must be an instance of decimal, float returned.

Anyway type decimal not exists.

I can use float for typping, but is this safe and good? The point is that with the float type there can be numerical errors (Float or decimal for prices?).

like image 267
jilo Avatar asked Aug 23 '17 19:08

jilo


1 Answers

Don't listen to recommendation to use floats for money values. It's really dangerous, because floating numbers cannot guarantee the accurate comparison of non-integer values.

Good solution is to use integers with multipliers. The best solution is to create ValueObject which represents type money.

like image 57
Alex Avatar answered Oct 03 '22 05:10

Alex