Shermaine Chaingan
Shermaine Chaingan

Reputation: 242

Adding Currency Value using php

I tried this code to add the value that is formatted currency but when i tried to add its giving me different value.

$item1="50,000.00";
$item2="1,000.00";

echo $total=(number_format($item1+$item2,2));

Output:51.00

Expected Output: 51,000.00

Upvotes: 0

Views: 201

Answers (1)

Oleks
Oleks

Reputation: 1633

The number_format function requires the first argument to be float, but as there is a comma in values php can't define the fractional part of the number. So firstly you need to remove the comma and then convert string to float type.

<?php
$item1="50,000.00";
$item2="1,000.00";

$itemFloat1 = floatval(str_replace(",", "", $item1));
$itemFloat2 = floatval(str_replace(",", "", $item2));

echo $total= number_format($itemFloat1 + $itemFloat2, 2);

Upvotes: 1

Related Questions