简体   繁体   中英

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?

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);
}

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

number_format($original_num/100,2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM