Skip to content

Commit

Permalink
fix(geometries): Fix stringifyFloat to correctly format number
Browse files Browse the repository at this point in the history
We missed the "." here and thus PHP formatted numbers with the default precision of 6 and prefixed it with whitespaces.
See PHP docs: https://www.php.net/manual/en/function.sprintf.php

This has been addressed by using the `json_encode` function to print the
float. This function uses PHP's `serialize_precision` instead, which
by default uses a similar algorithm to the one PostGIS uses for
printing out the float in a minimal representation and also
allows to print out at the maximum precision, as long as the
user did not change the serialization precision config.

Thanks @ronnypolloqueri for reporting this.

(cherry picked from commit 3c364e3)
  • Loading branch information
saibotk committed Jan 2, 2025
1 parent d37f0d5 commit 4e2a8fb
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## Unreleased

### Fixed

- Fixed only using a precision of 6 decimal digits in WKT, now uses the maximum precision

## [1.7.0](https://github.com/clickbar/laravel-magellan/tree/1.7.0) - 2024-12-27

### Added
Expand Down
6 changes: 4 additions & 2 deletions src/Data/Geometries/GeometryHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ public static function assertValidGeometryInput(int $minCount, string $class, ar

public static function stringifyFloat($float): string
{
// normalized output among locales
return trim(trim(rtrim(sprintf('%15F', $float), '0'), '.'));
// Use json_encode to use serialization precision instead of
// PHP's default format precision.
// See https://wiki.php.net/rfc/precise_float_value
return json_encode($float);
}
}
9 changes: 9 additions & 0 deletions tests/Generator/WKT/WKTGeneratorPointTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,12 @@

expect($pointWKT)->toBe('SRID=4326;POINT ZM(8.12345 50.12345 10 20)');
})->group('WKT Point');

// Test the float precision of the WKT generator
test('can generate 2D WKT Point with high float precision', function () {
$point = Point::make(8.1234567890123456789, 50.123456789012344);

$pointWKT = $this->generator->generate($point);

expect($pointWKT)->toBe('POINT(8.123456789012346 50.123456789012344)');
})->group('WKT Point');

0 comments on commit 4e2a8fb

Please sign in to comment.