user3636096
user3636096

Reputation: 3

Comparing money amount in php

After having checked everywhere in vain I decided to post this problem here. I am Working on an online shop where the client needs to show automatically a "free shipping label" for all items that cost 100€ or more. I did make a function that worked with plain numbers (80€), but when the price is in this format (2.453,90€) it doesn´t.

I would really appreciate your help if you could shed some light on this issue. Thanks in advance

Upvotes: 0

Views: 875

Answers (3)

Álvaro González
Álvaro González

Reputation: 146578

Stringified data types are a not uncommon beginner error. You should always handle numbers as native numbers and only convert to string when printing them.

When you use numbers, good old comparison operators become useful.

Upvotes: 1

AMDG
AMDG

Reputation: 975

You could use regular expressions to transforms formatted numbers in raw numbers.

$number = preg_replace('/\./', '', $number);
$number = preg_replace('/,/', '.', $number);

You could also store raw numbers instead of formatted numbers.

Upvotes: 1

Volkan Ulukut
Volkan Ulukut

Reputation: 4228

just remove dot and put dot instead of comma for php to recognize this as a number:

$plainNumber = floor(str_replace(",",".",str_replace(".","","2.453,90")));
if($plainNumber >= 100)
{
    //do intended stuff
}

Upvotes: 1

Related Questions