Math.php 10.7 KB
Newer Older
Ketan's avatar
Ketan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Locale
 * @copyright  Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id$
 */


/**
 * Utility class for proxying math function to bcmath functions, if present,
 * otherwise to PHP builtin math operators, with limited detection of overflow conditions.
 * Sampling of PHP environments and platforms suggests that at least 80% to 90% support bcmath.
 * Thus, this file should be as light as possible.
 *
 * @category   Zend
 * @package    Zend_Locale
 * @copyright  Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

class Zend_Locale_Math
{
    // support unit testing without using bcmath functions
    public static $_bcmathDisabled = false;

    public static $add   = array('Zend_Locale_Math', 'Add');
    public static $sub   = array('Zend_Locale_Math', 'Sub');
    public static $pow   = array('Zend_Locale_Math', 'Pow');
    public static $mul   = array('Zend_Locale_Math', 'Mul');
    public static $div   = array('Zend_Locale_Math', 'Div');
    public static $comp  = array('Zend_Locale_Math', 'Comp');
    public static $sqrt  = array('Zend_Locale_Math', 'Sqrt');
    public static $mod   = array('Zend_Locale_Math', 'Mod');
    public static $scale = 'bcscale';

    public static function isBcmathDisabled()
    {
        return self::$_bcmathDisabled;
    }

    /**
     * Surprisingly, the results of this implementation of round()
     * prove better than the native PHP round(). For example, try:
     *   round(639.795, 2);
     *   round(267.835, 2);
     *   round(0.302515, 5);
     *   round(0.36665, 4);
     * then try:
     *   Zend_Locale_Math::round('639.795', 2);
     */
    public static function round($op1, $precision = 0)
    {
        if (self::$_bcmathDisabled) {
            $op1 = round($op1, $precision);
            if (strpos((string) $op1, 'E') === false) {
                return self::normalize(round($op1, $precision));
            }
        }

        if (strpos($op1, 'E') !== false) {
            $op1 = self::floatalize($op1);
        }

        $op1    = trim(self::normalize($op1));
        $length = strlen($op1);
        if (($decPos = strpos($op1, '.')) === false) {
            $op1 .= '.0';
            $decPos = $length;
            $length += 2;
        }
        if ($precision < 0 && abs($precision) > $decPos) {
            return '0';
        }

        $digitsBeforeDot = $length - ($decPos + 1);
        if ($precision >= ($length - ($decPos + 1))) {
            return $op1;
        }

        if ($precision === 0) {
            $triggerPos = 1;
            $roundPos   = -1;
        } elseif ($precision > 0) {
            $triggerPos = $precision + 1;
            $roundPos   = $precision;
        } else {
            $triggerPos = $precision;
            $roundPos   = $precision -1;
        }

        $triggerDigit = $op1[$triggerPos + $decPos];
        if ($precision < 0) {
            // zero fill digits to the left of the decimal place
            $op1 = substr($op1, 0, $decPos + $precision) . str_pad('', abs($precision), '0');
        }

        if ($triggerDigit >= '5') {
            if ($roundPos + $decPos == -1) {
                return str_pad('1', $decPos + 1, '0');
            }

            $roundUp = str_pad('', $length, '0');
            $roundUp[$decPos] = '.';
            $roundUp[$roundPos + $decPos] = '1';

            if ($op1 > 0) {
                if (self::$_bcmathDisabled) {
                    return Zend_Locale_Math_PhpMath::Add($op1, $roundUp, $precision);
                }
                return self::Add($op1, $roundUp, $precision);
            } else {
                if (self::$_bcmathDisabled) {
                    return Zend_Locale_Math_PhpMath::Sub($op1, $roundUp, $precision);
                }
                return self::Sub($op1, $roundUp, $precision);
            }
        } elseif ($precision >= 0) {
            return substr($op1, 0, $decPos + ($precision ? $precision + 1: 0));
        }

        return (string) $op1;
    }

    /**
     * Convert a scientific notation to float
     * Additionally fixed a problem with PHP <= 5.2.x with big integers
     *
     * @param string $value
     */
    public static function floatalize($value)
    {
        $value = strtoupper($value);
        if (strpos($value, 'E') === false) {
            return $value;
        }

        $number = substr($value, 0, strpos($value, 'E'));
        if (strpos($number, '.') !== false) {
            $post   = strlen(substr($number, strpos($number, '.') + 1));
            $mantis = substr($value, strpos($value, 'E') + 1);
            if ($mantis < 0) {
                $post += abs((int) $mantis);
            }

            $value = number_format($value, $post, '.', '');
        } else {
            $value = number_format($value, 0, '.', '');
        }

        return $value;
    }

    /**
     * Normalizes an input to standard english notation
     * Fixes a problem of BCMath with setLocale which is PHP related
     *
     * @param   integer  $value  Value to normalize
     * @return  string           Normalized string without BCMath problems
     */
    public static function normalize($value)
    {
        $convert = localeconv();
        $value = str_replace($convert['thousands_sep'], "",(string) $value);
        $value = str_replace($convert['positive_sign'], "", $value);
        $value = str_replace($convert['decimal_point'], ".",$value);
        if (!empty($convert['negative_sign']) and (strpos($value, $convert['negative_sign']))) {
            $value = str_replace($convert['negative_sign'], "", $value);
            $value = "-" . $value;
        }

        return $value;
    }

    /**
     * Localizes an input from standard english notation
     * Fixes a problem of BCMath with setLocale which is PHP related
     *
     * @param   integer  $value  Value to normalize
     * @return  string           Normalized string without BCMath problems
     */
    public static function localize($value)
    {
        $convert = localeconv();
        $value = str_replace(".", $convert['decimal_point'], (string) $value);
        if (!empty($convert['negative_sign']) and (strpos($value, "-"))) {
            $value = str_replace("-", $convert['negative_sign'], $value);
        }
        return $value;
    }

    /**
     * Changes exponential numbers to plain string numbers
     * Fixes a problem of BCMath with numbers containing exponents
     *
     * @param integer $value Value to erase the exponent
     * @param integer $scale (Optional) Scale to use
     * @return string
     */
    public static function exponent($value, $scale = null)
    {
        if (!extension_loaded('bcmath')) {
            return $value;
        }

        $split = explode('e', $value);
        if (count($split) == 1) {
            $split = explode('E', $value);
        }

        if (count($split) > 1) {
            $value = bcmul($split[0], bcpow(10, $split[1], $scale), $scale);
        }

        return $value;
    }

    /**
     * BCAdd - fixes a problem of BCMath and exponential numbers
     *
     * @param  string  $op1
     * @param  string  $op2
     * @param  integer $scale
     * @return string
     */
    public static function Add($op1, $op2, $scale = null)
    {
        $op1 = self::exponent($op1, $scale);
        $op2 = self::exponent($op2, $scale);

        return bcadd($op1, $op2, $scale);
    }

    /**
     * BCSub - fixes a problem of BCMath and exponential numbers
     *
     * @param  string  $op1
     * @param  string  $op2
     * @param  integer $scale
     * @return string
     */
    public static function Sub($op1, $op2, $scale = null)
    {
        $op1 = self::exponent($op1, $scale);
        $op2 = self::exponent($op2, $scale);
        return bcsub($op1, $op2, $scale);
    }

    /**
     * BCPow - fixes a problem of BCMath and exponential numbers
     *
     * @param  string  $op1
     * @param  string  $op2
     * @param  integer $scale
     * @return string
     */
    public static function Pow($op1, $op2, $scale = null)
    {
        $op1 = self::exponent($op1, $scale);
        $op2 = self::exponent($op2, $scale);
        return bcpow($op1, $op2, $scale);
    }

    /**
     * BCMul - fixes a problem of BCMath and exponential numbers
     *
     * @param  string  $op1
     * @param  string  $op2
     * @param  integer $scale
     * @return string
     */
    public static function Mul($op1, $op2, $scale = null)
    {
        $op1 = self::exponent($op1, $scale);
        $op2 = self::exponent($op2, $scale);
        return bcmul($op1, $op2, $scale);
    }

    /**
     * BCDiv - fixes a problem of BCMath and exponential numbers
     *
     * @param  string  $op1
     * @param  string  $op2
     * @param  integer $scale
     * @return string
     */
    public static function Div($op1, $op2, $scale = null)
    {
        $op1 = self::exponent($op1, $scale);
        $op2 = self::exponent($op2, $scale);
        return bcdiv($op1, $op2, $scale);
    }

    /**
     * BCSqrt - fixes a problem of BCMath and exponential numbers
     *
     * @param  string  $op1
     * @param  integer $scale
     * @return string
     */
    public static function Sqrt($op1, $scale = null)
    {
        $op1 = self::exponent($op1, $scale);
        return bcsqrt($op1, $scale);
    }

    /**
     * BCMod - fixes a problem of BCMath and exponential numbers
     *
     * @param  string  $op1
     * @param  string  $op2
     * @return string
     */
    public static function Mod($op1, $op2)
    {
        $op1 = self::exponent($op1);
        $op2 = self::exponent($op2);
        return bcmod($op1, $op2);
    }

    /**
     * BCComp - fixes a problem of BCMath and exponential numbers
     *
     * @param  string  $op1
     * @param  string  $op2
     * @param  integer $scale
     * @return string
     */
    public static function Comp($op1, $op2, $scale = null)
    {
        $op1 = self::exponent($op1, $scale);
        $op2 = self::exponent($op2, $scale);
        return bccomp($op1, $op2, $scale);
    }
}

if (!extension_loaded('bcmath')
    || (defined('TESTS_ZEND_LOCALE_BCMATH_ENABLED') && !TESTS_ZEND_LOCALE_BCMATH_ENABLED)
) {
    #require_once 'Zend/Locale/Math/PhpMath.php';
    Zend_Locale_Math_PhpMath::disable();
}