From fda310f1e7c9235c1466b55d829339d2ee655854 Mon Sep 17 00:00:00 2001 From: "Edward Z. Yang" Date: Tue, 20 May 2008 17:48:15 +0000 Subject: [PATCH] Update UnitConverter to deal more correctly with X.XX... decimals. Not complete. git-svn-id: http://htmlpurifier.org/svnroot/htmlpurifier/trunk@1749 48356398-32a2-884e-a903-53898d9a118a --- library/HTMLPurifier/UnitConverter.php | 18 ++++++++++++------ tests/HTMLPurifier/UnitConverterTest.php | 8 ++++++++ 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/library/HTMLPurifier/UnitConverter.php b/library/HTMLPurifier/UnitConverter.php index 2410c7e9..f4d29037 100644 --- a/library/HTMLPurifier/UnitConverter.php +++ b/library/HTMLPurifier/UnitConverter.php @@ -149,12 +149,18 @@ class HTMLPurifier_UnitConverter // Calculations will always be carried to the decimal; this is // a limitation with BC (we can't set the scale to be negative) $new_log = (int) floor(log($n, 10)); - - $rp = $sigfigs - $new_log - $log - 1; - if ($rp < 0) $rp = 0; - - $n = bcadd($n, '0.' . str_repeat('0', $rp) . '5', $rp + 1); - $n = bcdiv($n, '1', $rp); + $rp = $sigfigs - $new_log - 1; + //echo "----\n"; + //echo "$n\nsigfigs = $sigfigs\nnew_log = $new_log\nlog = $log\nrp = $rp\n"; + if ($rp >= 0) { + $n = bcadd($n, '0.' . str_repeat('0', $rp) . '5', $rp + 1); + $n = bcdiv($n, '1', $rp); + } else { + if ($new_log + 1 >= $sigfigs) { + $n = bcadd($n, '5' . str_repeat('0', $new_log - $sigfigs)); + $n = substr($n, 0, $sigfigs) . str_repeat('0', $new_log + 1 - $sigfigs); + } + } if (strpos($n, '.') !== false) $n = rtrim($n, '0'); $n = rtrim($n, '.'); diff --git a/tests/HTMLPurifier/UnitConverterTest.php b/tests/HTMLPurifier/UnitConverterTest.php index b2c1cb6a..80ba70dc 100644 --- a/tests/HTMLPurifier/UnitConverterTest.php +++ b/tests/HTMLPurifier/UnitConverterTest.php @@ -39,4 +39,12 @@ class HTMLPurifier_UnitConverterTest extends HTMLPurifier_Harness $this->assertConversion('0.3937in', '1cm'); } + function testRounding() { + $this->assertConversion('100pt', '1.389in'); + $this->assertConversion('1000pt', '13.89in'); + $this->assertConversion('10000pt', '138.9in'); + $this->assertConversion('100000pt', '1389in'); + $this->assertConversion('1000000pt', '13890in'); + } + }