user1433479
user1433479

Reputation: 135

Adding up currency values

I'm trying to add up some currency using PHP.

The values I'm trying to add up are like this:

The first one is 2 thousand euro's, the second one is 10 euro's and 50 cents.

I want to add these up so it comes up to a total of 2621,20 euro's (if I calculated it correctly).

I tried passing the values to floats but that didn't give me the result I expected. Here is what I have made so far:

$rent = $product->get_price_html();
$rent_int = (int) preg_replace('|[^0-9]|i', '', $rent);

// I'm working in wordpress, but the values are the same as the above ones

$gwl = get_post_meta( $post->ID, 'g/w/l_prijs', true);
$tti = get_post_meta( $post->ID, 't/t/i_prijs', true);
$heffing = get_post_meta( $post->ID, 'heffingen_prijs', true);
$verzekering = get_post_meta( $post->ID, 'verzekering_prijs', true);

$total = (float)$rent_int + (float)$gwl + (float)$tti + (float)$heffing + (float)$verzekering;

As you can see I'm removing everything that's not a number from the rent value. Ofcourse this causes a major issue when the rent value is a float and not an int.

How would I go about calculating currency properly? I'm not sure how it's done in other countries, but the dot represents 1000 and a comma is the cents.

Upvotes: 0

Views: 69

Answers (2)

fie
fie

Reputation: 416

It appears that you are using Woocommerce.

If I am not mistaken if you should be able to do:

$rent = $product->get_price();

And then get rid of all of that preg_replace non-sense.

This should set $rent to a floating point value that you can do your maths on.

http://docs.woothemes.com/wc-apidocs/source-class-WC_Product.html#752-759

Upvotes: 1

edmondscommerce
edmondscommerce

Reputation: 2011

If you are wanting to use the comma as a decimal then you can't strip it out.

Try this line instead of your current line to get the $rent_int value

$rent_int = (float) str_replace(',','.',preg_replace('|[^0-9,]|i', '', $rent));

Obviously this is no longer an int (its a float) but I leave tidying up your variable names to you.

Upvotes: 0

Related Questions