Sylius: How to set a Product price correctly

Created on 9 Feb 2016  路  9Comments  路  Source: Sylius/Sylius

Guys this should be trivial but I鈥檓 not completely sure about how to set a price with decimal part in a product.
I鈥檓 doing a migration script creating products programmatically and I鈥檓 using $variant->setPrice(); that accepts only an integer.

Which helper class should I use?

Help Wanted

Most helpful comment

"If I had a dime for every time I've seen someone use FLOAT to store currency, I'd have $999.997634" -- Bill Karwin

All 9 comments

@xantrix Sylius operates on all money values as integers. So if you want 99.99 price -> use 9999. Let me know if you need any further help. I will leave it open.

@pjedrzejewski this is quite odd solution IMO. What's the reason behind not using floats?

"If I had a dime for every time I've seen someone use FLOAT to store currency, I'd have $999.997634" -- Bill Karwin

@pjedrzejewski You could also use a value object to represent money, not sure if this is something you want in Sylius, but it might improve usability.

So you would do something like this to alter a products price:

$variant->setPrice(new Money(12.99));

@steffenbrem we plan to introduce the money value object. Probably https://github.com/moneyphp/money but there will be a separate RFC about that :)

Great, so it should be simple as this:

//two examples
//4,912 := 491200
//49.12 := 4912
$intPrice =  (int)( number_format($data['old_db_price'], 2, '.', '') * 100);
$product->getMasterVariant()->setPrice($intPrice);

Thanks for your support :)

P.s. :+1: for money value object.

@xantrix Yes you are right, multiply your floats or doubles by 100 and cast it to be an integer and you are doing it fine :+1:.

I think this issue can be closed, no?

@steffenbrem sure! Thanks!

Was this page helpful?
0 / 5 - 0 ratings