Forums

Number Format for PHP math processing On Submit CFv5

ITadminguy 05 Apr, 2018
Hey Bob.

I checked prior posts for a similar problem without luck.

I have a simple math calculation on a form that works well as follows:

500 - 50 = 450

This is an On Submit PHP code that pulls the data from the form. For simplicity I changed the field names for easy understanding.

<?php
$form->data['net_price'] = $form->data['price'] - $form->data['discount'];
?>

450 = 500 - 50

price is a stored value from a prior form entry = 500
discount is a radio button on the current form where selection was 50
net_price is the formula

This works great so long as there are no commas or periods in the data.

If my price from the prior form is 4,300.00 in the database, and 4,300.00 is read into the current form as the price, the php math calculation does not work.

Instead, when the price is 4,300.00 and the discount is 50, the net price is -46 (which should be 4,250.00)

It looks like if I use a comma or a period in the number in the database, when the number is called up into a new form, the php formula does not compte.

Have you run across this problem? Should all amouunts be saved into the forms and database without "," or "." in the format of the number?

Or can the php formula adjust for commas and periods in the numbers

Thanks in advance.

healyhatman 05 Apr, 2018
If you insist on storing commas in your database for whatever reason:
<?php

$form->data['net_price'] = str_replace("," , "", $form->data['price']) - $form->data['discount'];

?>
GreyHead 05 Apr, 2018
Hi itadminguy,

. . . and better to clean the data before you save it - you can always re-format later if you need to.

Bob
ITadminguy 05 Apr, 2018
Yes, adding this worked perfect

str_replace("," , "", $form->data['price'])

The output is "4250"

Also, there is no need to remove the "." in front of the ".00" cents as it is stored in the database.

This topic is locked and no more replies can be posted.