-
-
Save Zvax/1a35a8b5ed2a02dc2610f73aad249611 to your computer and use it in GitHub Desktop.
formatting numbers to an arbitrary number of decimals while removing zeroes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php declare(strict_types=1); | |
namespace Test; | |
use PHPUnit\Framework\TestCase; | |
/* | |
* We want to format numbers with , as decimal separator and space as thousand separator | |
* removing any trailling 0 | |
* and any excedent decimals past a certain number | |
* | |
* we assume that the number separator is always . | |
* | |
*/ | |
function format(string $number, int $decimal = 0): string | |
{ | |
if (strpos($number, '.') === false) { | |
return makeNumber($number); | |
} | |
[$whole, $fraction] = explode('.', $number); | |
return makeNumber($whole) . ($fraction > 0 ? (',' . makeDecimals($fraction, $decimal)) : ''); | |
} | |
function makeDecimals(string $decimals, int $limit): string | |
{ | |
if (\strlen($decimals) === 0) { | |
throw new \LogicException('we are formatting an empty string'); | |
} | |
return substr(rtrim($decimals, '0'), 0, $limit); | |
} | |
function makeNumber(string $number): string | |
{ | |
return ltrim(strrev(chunk_split(strrev($number), 3, ' ')), ' '); | |
} | |
class SomethingTest extends TestCase | |
{ | |
/** @test */ | |
public function basic_stuff(): void | |
{ | |
$this->assertSame(1.04, (float)'1.04'); | |
} | |
/** @test */ | |
public function trims_decimals(): void | |
{ | |
$this->assertSame('003', makeDecimals('0030', 3)); | |
$this->assertSame('003', makeDecimals('0030', 4)); | |
$this->assertSame('0034', makeDecimals('00345', 4)); | |
} | |
/** @test */ | |
public function spaces_number(): void | |
{ | |
$this->assertSame('1 300', makeNumber('1300')); | |
$this->assertSame('300', makeNumber('300')); | |
} | |
/** @test */ | |
public function pads_stuff(): void | |
{ | |
$this->assertSame('1', format('1.00', 2)); | |
$this->assertSame('1', format('1.00', 4)); | |
$this->assertSame('0,25', format('0.25', 4)); | |
$this->assertSame('1 000,25', format('1000.25', 4)); | |
$this->assertSame('1,044', format('1.044', 3)); | |
$this->assertSame('0,24', format('0.24000', 5)); | |
$this->assertSame('0,24546', format('0.24546', 5)); | |
$this->assertSame('0,2454', format('0.24546', 4)); | |
$this->assertSame('6 500', format('6500.00', 0)); | |
$this->assertSame('3 760,54', format('3760.54', 2)); | |
$this->assertSame('3 760,54', format('3760.541234', 2)); | |
$this->assertSame('3 760', format('3760.00', 2)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment