使用PHP以非标准货币格式呈现整数

时间:2015-05-06 17:26:41

标签: php

我正在制作一个PHP脚本,该脚本将用作RPG的一部分。货币的价值存储为整数,但需要略有不同。

例如,如果值为125050,则应显示为12 gold, 50 silver and 50 copper。然而,为了使问题进一步复杂化,有时代码将用于不同的系统,其中每个系统中的10个等于下一个系统,因此125050将是1250 gold, 5 silver (and no copper)。此外,一些会议将要求使用第四个货币单位(可能是铂金),这将遵循相同的模式。

鉴于我知道单位除数将是10或100,我需要一种以正确格式呈现整数值的方法。怎么办呢?

我的想法是将int转换为字符串并拾取字符,但我宁愿使用纯粹的数学方法,这样我也可以将int分成int数组,如下所示:

// 125050
//  =
$money(
    'copper'=>50,
    'silver'=>50,
    'gold'=>12,
    'platinum'=>0
); 

更新:在修补各种数学函数后,我回忆起有一个名为Modulus的运算符。我必须抬头看看。1

任何方式我都会把这个小混乱弄得一团糟:

<?php
// ...
$c = $this->balance % $this->unitSize;
$s = floor($this->balance / $this->unitSize) % $this->unitSize;
$g = floor( ($this->balance / ($this->unitSize *2)) ) % $this->unitSize;

我不知道这是一个特别优雅的解决方案,还是一个工作的解决方案。

1 个答案:

答案 0 :(得分:1)

玩弄这个并得到一些适用于你想要使用的任何面额系统的东西。

假设一个面额数组,它映射你的面额值:

maven-glassfish-plugin-2.1.pom.md5

然后是测试金额

$denominations = [
        "Hundred Dollar Bill" => 100,
        "Twenty Dollar Bill" => 20,
        "Ten Dollar Bill" => 10,
        "Five Dollar Bill" => 5,
        "One Dollar Bill" => 1,
        "Quarter" => 0.25,
        "Dime" => 0.1,
        "Nickel" => 0.05,
        "Penny" => 0.01
    ];

此函数将根据您传入其中的面额数组返回逗号描述的金额细分。

$amount = 312.58;

所以正在运行function breakdownDenominations($amount, $denominations) { arsort($denominations); // sort the denomination values from high to low $count = array(); foreach ($denominations as $key=>$value) { while ($amount >= $value) { $amount = round($amount - $value,2); // decrement by the value of the denomination if (!isset($count[$key])) { $count[$key] = 1; } else { $count[$key]++; // track the occurrence of each denomination } } } // you could return the $count array here if you want to do database stuff $breakdown = array(); foreach ($count as $key=>$value) { $breakdown[] = "$value $key"; // combine the keys with the value for formatting } return implode (", ",$breakdown); // combine the array into a comma-delineated string }

  

3百美元的钞票,1个10美元的钞票,2个1美元的钞票,2个季度,1个镍币,3个便士

显然它并不真正关心复数状态,但你应该可以根据任何面额表来修改它。