Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

eriktobben's avatar

How to calculate numbers with comma?

Hi!

I am trying to add VAT to some prices, but when I have a price with decimals, php ignores them.

Example:

Price 239,20 * VAT 1,25 = 298,75 (should be 299)

How can I get PHP to understand that I want to include the numbers after the comma as well?

0 likes
14 replies
jlrdw's avatar

Look into the number format functions. And are you sure this isn't stored as a string?

eriktobben's avatar

The field is a string. What should it be to allow for commas?

mstnorris's avatar

Why not store currency as integers in their lowest form, for example £100 would be 10000pence = 10000.

bestmomo's avatar

If you have a decimal value use decimal field, it's for this case.

eriktobben's avatar

Okey, so I've tried using decimal field, but when trying this in Sequel Pro I get the following error:

The row was not written to the MySQL database. You probably haven't changed anything. Reload the table to be sure that the row exists and use a primary key for your table.

My field looks like this: Field: price Type: decimal Length: 11,0 Default: 0

Snapey's avatar

because you have a string with commas. I'm not sure how, but you have to set the locale so that php knows that the comma is decimal notation.

jlrdw's avatar

Again learn string functions. Could even be done in JavaScript.

frezno's avatar

@eriktobben

My field looks like this: Field: price Type: decimal Length: 11,0 Default: 0

that's not correct for what you want to achieve. You have to use eg 8,3 as length for your decimal field, which means the number can be a total of 8 digits and there are 3 digits on the right side of the comma, eg 12350,750

eriktobben's avatar

@frezno Ahh, now I get it! Thanks!

My problem now is that it wont take comma, but accepts period. Is this easy to fix on database end, or should I just replace commas with periods when writing to db and replace them back, when editing?

Snapey's avatar

use numberformatter, it is what it's for

frezno's avatar

@eriktobben

the input to your database has to be using a period. The number will be displayed according to your local setting though.

For the output in your programm you can write a little helper function to make things easier. Something like that:

/**
 * Format the price and add the currency symbol
 *
 * @param int $price
 * @param string $currency
 * @param int $post
 *
 * @return string
 */
function format_price($price, $currency = '€', $post = 1)
{
    if ($post === 1)
    {
        $formatted_price = number_format($price, 2, ',', '.') . ' ' . $currency;
    } else {
        $formatted_price = $currency.number_format($price, 2);
    }

    return $formatted_price;
}
1 like
eriktobben's avatar

Thank you all for helping me on this, it works perfectly!

Please or to participate in this conversation.