#
#
# artur #2014-10-06 23:54:09
PHP
# artur #, 2014-10-06 23:54:09

Storing prices in kopecks (int). How to output correctly?

Hello.
I read a lot of opinions, on different forums, it was decided to abandon decimal in favor of int.
It is clear that while maintaining the price, it must be multiplied by 100, and divided when outputting.
For example:
We take the price of 1,500 rubles. We multiply 50 kopecks (1500.50) by 100, we get 150,050 kopecks - saved.
Output: 150050/100, we get 1500.5 - we see that 0 is lost at the end.
How correctly to withdraw 50 kopecks in the end? I also don’t understand what to do if 00 kopecks. Perhaps someone has a ready-made "easy" function, I will be grateful for help, advice.
I will add: there is only one solution so far:

public static function price($price) {
       return $result = number_format($price/100, 2, ',', ' ').' руб';
    }

- how correct?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
K
KorsaR-ZN, 2014-10-07
@passshift

Probably there will be no other solution, your good one. Is there anything else needed?)
Only $result = , there is still superfluous :)

R
Rrooom, 2014-10-07
@Rrooom

In vain. This is redundant work and a source of errors. Use decimal.

D
Dmitry, 2014-10-07
@By_Engine

SQL has a float data type that allows you to store floating point numbers

A
Alexander Kubintsev, 2014-10-07
@akubintsev

PostgreSQL has a wonderful data type for just such a thing. called numeric

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question