1

I have done this calculation:

$number = round(count($exc)/ count($grades),2,PHP_ROUND_HALF_UP);

When save,I have to save it into a field of an existing table which is a longtext type. The numbers got saved but become very long, something like 0.200000000000000011102230246251565404236316680908203125 I think this might cause extra db storage. When I query the numbers, they are still rounded as 2 digital. So, that's an extra converting job. I would like to learn how to save those numbers as rounded number?

4
  • 2
    Why would you want to store a number as a longtext field? Commented Aug 11, 2012 at 8:05
  • Why are you using a textual type to store numerical data? MySQL has a number of numeric datatypes (INT, NUMERIC, FLOAT, etc), why not use one of those? Using the wrong type for the data you're storing at best robs you of flexibility and at worst will result in incorrect results for SQL operations. You will not get the items back in the order you expect if you try sorting them, for example Commented Aug 11, 2012 at 8:06
  • because I have to save it into an existing table which is not for me to re-design. Commented Aug 11, 2012 at 8:06
  • Welcome to the wonderful world of floating point numbers. Commented Aug 11, 2012 at 8:13

1 Answer 1

0

You can use PHP sprintf function coupled with format specifier like so:

$number = sprintf("%.3f", round(count($exc)/ count($grades),2,PHP_ROUND_HALF_UP));

If you need more info about that take a look at sprintf PHP documentation here https://www.php.net/manual/en/function.sprintf.php .

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.