adhirath wcities
adhirath wcities

Reputation: 71

How to do calculation on comma separated values and restore comma in PHP

I have a few values, some of these are comma separated and some aren't. I would like to do calculations with these values and restore the comma to it's original position.

eg:

Number: 5,125 + 5 = 5,130

Number: 999 + 5 = 1,004

Number: 150 + 5 = 155

Number: 1,004 - 5 = 999

This is what I thought I should do, but I'm unable to restore the value.

echo str_replace(',', '', $a) + 5;

Upvotes: 0

Views: 244

Answers (2)

V.Volkov
V.Volkov

Reputation: 739

$a = '2,456'; // 2,456
$n = floatval( str_replace( ',', '.', $a ) ); // 2.456
// math operations go here
echo number_format( $n, 2, ',', '' ); // 2,46

Upvotes: 0

S N Sharma
S N Sharma

Reputation: 1526

Try this

echo number_format(str_replace(',', '', $a) + 5);

Upvotes: 2

Related Questions