-1

I would like to turn an int value (21, VAT) into a float (factor) 1.21. So that I can turn a product price into the price including tax.

Some function gives me the int 21, which I would gratefully like to use. I used so far;

Really ugly

$taxRate = 21; // this come from a function in PrestaShop in case you wonder
$factor = (float)"1.$taxRate"; // 1.21

Feels more savvy

$taxRate = 21;
$factor = 1+($taxRate/100); // 1.21

I really think I'm missing some function of other interesting syntax. I know it seems trivial but I feel both options are so ugly and long, and might even kick back later.

Matt
  • 136
  • 2
  • 17
  • 2
    Careful: `echo serialize(1+(33/100));` and `echo serialize((float)"1.33");` – AbraCadaver Feb 08 '18 at 20:39
  • @AbraCadaver that outputs `1.3300000000000001`. maybe `echo (string) (1 + (33/100));` ? – Kidus Feb 08 '18 at 20:41
  • 2
    @Kidus I know, they want a float and I'm showing that may be problematic. – AbraCadaver Feb 08 '18 at 20:43
  • @AbraCadaver why does it become a crazy number? `1.3300000000000000710542735760100185871124267578125 ` – Matt Feb 08 '18 at 20:56
  • 1
    https://stackoverflow.com/questions/588004/is-floating-point-math-broken – AbraCadaver Feb 08 '18 at 21:00
  • Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) –  Feb 08 '18 at 21:01
  • Not only is the first code really ugly, it is really wrong. What happens if Trump lowers the tax rate to `$taxRate = 9`. Then your `$factor` will be `1.9`. – BareNakedCoder Feb 08 '18 at 21:12
  • @BareNakedCoder that's why it felt ugly I guess, thank you for the example! – Matt Feb 08 '18 at 21:41
  • you can add by 100 to make it 121 instead of 1.21. Then convert the integer to decimal after you calculate the final answer – CSK Feb 08 '18 at 22:20

1 Answers1

-1

Wanted something like this? Haha) Do not make it harder than it is!

class BeatifulTaxFactorCalculator
{
    private $taxRate;

    /**
     * @return mixed
     */
    public function getTaxRate()
    {
        return $this->taxRate;
    }

    /**
     * @param mixed $taxRate
     */
    public function setTaxRate($taxRate)
    {
        $this->taxRate = $taxRate;
    }
    private function getBeautifulTaxRate()
    {
        return $this->getTaxRate()/100;
    }

    public function getBeautifulPriceFactor(){
        return 1 + $this->getBeautifulTaxRate();
    }

    final static function calculatePriceFactorReallyUgly($taxRate){
        return (float)"1.$taxRate";
    }

    final static function calculatePriceFactorMoreSavvy($taxRate){
        return 1+($taxRate/100);
    }
}

$factorUgly = BeatifulTaxFactorCalculator::calculatePriceFactorReallyUgly(21);
$factorUgly2 = BeatifulTaxFactorCalculator::calculatePriceFactorMoreSavvy(21);

$factorCalculator = new BeatifulTaxFactorCalculator();
$factorCalculator->setTaxRate(21);
$factorBeautiful = $factorCalculator->getBeautifulPriceFactor();