<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------

namespace app\common\library\utils;

/**
 * @package app\common\library\utils
 * @class Money
 * @author xzncit 2023-09-04
 */
class Money {

    /**
     * 金额格式
     * @param $num
     * @param int $decimals
     * @return string
     */
    public static function numberFormat($num, $decimals = 2){
        return number_format($num,$decimals);
    }

    /**
     * 格式化价格
     * @param $number
     * @param string $unit
     * @return array
     */
    public static function format($number,$unit=""){
        if (empty($number) || !is_numeric($number)) {
            return $number;
        }

        if ($number > 10000) {
            $leftNumber = floor($number / 10000);
            $rightNumber = round(($number % 10000) / 10000, 2);
            $number = floatval($leftNumber + $rightNumber);
        } else {
            $decimals = $number > 1 ? 2 : 6;
            $number = (float)number_format($number, $decimals, '.', '');
            $unit = "";
        }

        return ["price"=>$number,"unit"=>$unit];
    }

    /**
     * 获取格式化价格
     * @param $number
     * @param string $unit
     * @return array|string
     */
    public static function getFormat($number,$unit="万元"){
        $data = self::format($number,$unit);
        return $data["price"] . $data["unit"];
    }

    /**
     * 同比增长的函数
     * @param $a 今日数据
     * @param $b 上个期限的数据
     * @return string
     */
    public static function compare($a,$b){
        $a=(int)$a;
        $b=(int)$b;
        if($a == $b){
            return "0%";
        }else if($b == 0 && $a > 0){
            return "100%";
        }else if($a == 0 && $b > 0){
            return "-100%";
        }else if($a > $b){
            $c = round(($a - $b) / $b,2);
            $c = $c * 100;
            return $c . "%";
        }else if($a<$b){
            $c = round(($a - $b) / $b,2);
            $c = $c * 100;
            return $c . "%";
        }

        return "0%";
    }

}