Skip to content

Instantly share code, notes, and snippets.

@vudaltsov
Last active October 24, 2025 07:20
Show Gist options
  • Select an option

  • Save vudaltsov/0e99f66f56719b30480fc357828c940a to your computer and use it in GitHub Desktop.

Select an option

Save vudaltsov/0e99f66f56719b30480fc357828c940a to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
/**
* @return numeric-string
*/
function floatToString(float $float): string
{
$string = (string) $float;
if (!preg_match('~\.(\d+)E([+-])(\d+)$~', $string, $matches)) {
return $string;
}
if ($matches[2] === '+') {
/** @var numeric-string */
return number_format($float, thousands_separator: '');
}
$decimals = (int) $matches[3];
if ($matches[1] !== '0') {
$decimals += strlen($matches[1]);
}
/** @var numeric-string */
return number_format($float, $decimals, thousands_separator: '');
}
<?php
declare(strict_types=1);
use PHPUnit\Framework\Attributes\CoversFunction;
use PHPUnit\Framework\Attributes\TestWith;
use PHPUnit\Framework\TestCase;
#[CoversFunction('Typhoon\Type\Internal\floatToString')]
final class FloatToStringTest extends TestCase
{
#[TestWith([0, '0'])]
#[TestWith([-0, '0'])]
#[TestWith([0.0, '0'])]
#[TestWith([-0.0, '-0'])]
#[TestWith([0.012, '0.012'])]
#[TestWith([-0.012, '-0.012'])]
#[TestWith([7E-10, '0.0000000007'])]
#[TestWith([-7E-10, '-0.0000000007'])]
#[TestWith([123_456E-10, '0.0000123456'])]
#[TestWith([-123_456E-10, '-0.0000123456'])]
#[TestWith([1.234_567_89e23, '123456789000000003637248'])]
#[TestWith([-1.234_567_89e23, '-123456789000000003637248'])]
public function test(float $value, string $expected): void
{
$string = floatToString($value);
/** @phpstan-ignore staticMethod.alreadyNarrowedType */
self::assertIsNumeric($string);
self::assertSame($expected, $string);
self::assertSame($value, (float) $string);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment