views:

45

answers:

2

Hello

A have price data stored like this: 10.25

And percentage data like this 1.1100 (1.00%)

I need a function that accurately multiplies the price by the percentage. (in php)

Thanks

A: 
  • You should never store currency as a decimal. Always use intergers.

  • What is wrong with $money * ($percentage / 100)

Coronatus
A: 

It would probably be best if you split the storage of your percent data into two different fields if possible. But this will do what you're looking for, I believe. I split it into two functions - "convertPercentageDataToDecimal" extracts the percent from your data and converts it to a decimal, then "convertPercentageDataToDecimal" simply multiplies the price by the percent.

<?php 

$price = 10.25;
$percentageData = "1.1100 (1.00%)";

function multiplyPriceByPercentageData($price, $percentageData) {
    $percent = convertPercentageDataToDecimal($percentageData);
    return $price * $percent;
}

function convertPercentageDataToDecimal($percentageData) {
    $start = strpos($percentageData, '(') + 1;
    $length = strpos($percentageData, '%') - $start;
    $percent = substr($percentageData, $start, $length);
    return $percent / 100;
}

var_dump(convertPercentageDataToDecimal($percentageData));
var_dump(multiplyPriceByPercentageData($price, $percentageData));

// output:
//   float(0.01)
//   float(0.1025)
rmarscher