# How to remove decimals from calculation amount

I have a calculation like this (might be an easier way to work this out, but I am no maths boffin)

``````\$discount_percent = (\$reg_price-\$sale_price)/\$reg_price*100;
``````

This sometimes gives me something like 41.3333333333% which is obviously not what I want to display.

How would you remove all the .3 so it just shows 41% instead.

the best would be that if it is 41.5% or up to 41.9% it would round up to 42% and round down to 41.5% if less than 41.5%
LVL 1
###### Who is Participating?

Commented:
0

FreelancerCommented:
Use round() function
``````\$discount_percent = round((\$reg_price-\$sale_price)/\$reg_price*100);
``````
0

Commented:
0

FreelancerCommented:
Okay, number_format() affects what you display, round affects the result of the math op :)
1

Commented:
Marco: Exactly Right.  In my experience, the numeric values used in computations don't really need to be messed with - it's just the display that is the issue.  This kind of goes to the Model-View-Controller philosophy.  The Model carries the true  value (maybe including fractional cents) and the View presents a sensible "human" picture representation of the value.
0

Author Commented:
Man, you guys on Experts Exchange are the best! number_format() did the trick :)
0

FreelancerCommented:
Ray, you're always a step forward :)
1

Commented:

I would just add that when comparing floating point numbers, especially when looking for equality, you have an inherent risk in PHP.  See these links for details:
http://php.net/manual/en/language.operators.comparison.php
http://php.net/manual/en/language.types.float.php

One way to handle that risk is to use number_format() to about 6 decimals and compare the resulting strings.  Another is to learn about the "machine epsilon" and use that strategy.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.