user1331784
user1331784

Reputation: 188

PHP - Convert fixed number into decimal, using last 2 digits as the decimal places

I have a situation where all records in a CSV I'm parsing are currency, but the values are not separated by a decimal point. So for instance, value '1234' is actually '12.34', and '12345' is '123.45'.

I'm struggling to find a way to manually convert these values into decimals. I can't user number_format, because it will give me an output like so:

$original_num = 1234;

$formatted_num = number_format($original_num, '2', '.', '');

$formatted_num = 1234.00; //Output

The other issue is that sometimes I may have a value like '436257.5' after I combine two numbers, which is actually '436.2575' so I can't just manually push in a '.' two places from the end of the string. Should I consider formatting it differently while I'm parsing the file?

Upvotes: 1

Views: 5227

Answers (2)

Nabih Tabet
Nabih Tabet

Reputation: 29

Since number_format() function always adds 2 00 as decimal, you can divide the value by 100.

number_format($original_num/100,2);

Upvotes: 1

Amadan
Amadan

Reputation: 198324

Assuming you're using integers to always represent decimals with 2 places of precision after the decimal point, you just divide with 100 to insert the dot in the right place.

What do you mean, "combine"? You mean multiply? You should renormalise after each multiplication, and never get into a situation where you're representing decimals of differing precisions (unless you keep track of the precision, which you can do but it's pain in the ass and normally unnecessary).

function multiply($a, $b) {
  return round($a * $b / 100);
}

function format($a) {
  return sprintf("%.2f", $a / 100);
}

Upvotes: 3

Related Questions