Skip to content

float[] type #122

@mpiot

Description

@mpiot

Not really an issue, but a suggestion, I've implemented FloatArray locally for a project:

class FloatArray extends BaseArray
{
    protected const TYPE_NAME = 'float[]';

    /**
     * @param mixed $item
     */
    public function isValidArrayItemForDatabase($item): bool
    {
        return (\is_float($item) || \is_int($item) || \is_string($item))
            && preg_match('/^-?[0-9]+(?:\.[0-9]+)?$/', (string) $item);
    }

    /**
     * @param float|int|string|null $item Whole number
     */
    public function transformArrayItemForPHP($item): ?float
    {
        if (null === $item) {
            return null;
        }

        $isInvalidPHPInt = false === preg_match('/^-?[0-9]+(?:\.[0-9]+)?$/', (string) $item);
        if ($isInvalidPHPInt) {
            throw new ConversionException(sprintf('Given value of %s content cannot be transformed to valid PHP float.', var_export($item, true)));
        }

        return (float) $item;
    }
}

In that case, I do not verify the number of digits (https://www.postgresql.org/docs/current/datatype-numeric.html) depending on real (float4) or double precision (float8).
Doctrine natively not handle float4 (real) but only floa8(double precision), PHP have a precision of 14 digits. That's why I do not do the check (but in external library like here, seem important to do, if the user change the precision to 16 for exemple).

Name Storage Size Description Range
real 4 bytes variable-precision, inexact 6 decimal digits precision
double precision 8 bytes variable-precision, inexact 15 decimal digits precision

It seems there also have a min/max value like done with Integer array:

On most platforms, the real type has a range of at least 1E-37 to 1E+37 with a precision of at least 6 decimal digits. The double precision type typically has a range of around 1E-307 to 1E+308 with a precision of at least 15 digits. Values that are too large or too small will cause an error. Rounding might take place if the precision of an input number is too high. Numbers too close to zero that are not representable as distinct from zero will cause an underflow error.

  1. Check the min/max is not really difficult I think, do the same like done with IntegerArray
  2. Check the number of digits seen a more little difficult: convert to string, count number chars after the ".", and if scientific notation use the "E" ?

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions