Laravel-mongodb: How to insert document with field being NumberDecimal

Created on 21 Oct 2018  路  4Comments  路  Source: jenssegers/laravel-mongodb

I'm working on an app which requires strict decimal accuracy. Is it possible to insert a document and specify that certain fields are of type NumberDecimal? How would this be done using your API?

Most helpful comment

I'm using this way to in my project;

use MongoDB\BSON\Decimal128;
....
....
$record->yourField = new Decimal128($yourValue);
....
$record->save();

All 4 comments

(If I understand you correctly)

Mongo's decimal type is Double and php's soft-type is Float (single precision) so assuming this is sufficient precision, storing the data with this level of precision would be sufficient.

If you wish, on the presentation level, to only show particular bits of precision, you could store the data as an object with the number of decimals or bits of precision stored as a parameter.

You could then overload the magic getter for that value such that it checks for the precision parameter and returns the value as a massaged string, only showing the precision requested, performing the appropriate rounding etc as you see fit.

There are likely other ways to do this - I hope this helps.

Thank you for your reply. I understand what you're saying, but I'd like to avoid the entire scenario of rounding, decimal precision, etc.

I found this: https://docs.mongodb.com/manual/tutorial/model-monetary-data/

and I'd like to use the NumberDecimal type for a particular column but it's not clear to me how to achieve this using this API.

I'm using this way to in my project;

use MongoDB\BSON\Decimal128;
....
....
$record->yourField = new Decimal128($yourValue);
....
$record->save();

Works like a charm, thank you!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

viacheslavpleshkov picture viacheslavpleshkov  路  3Comments

sebastiaanluca picture sebastiaanluca  路  3Comments

phuocduy1988 picture phuocduy1988  路  3Comments

yupangestu picture yupangestu  路  3Comments

sanjay1688 picture sanjay1688  路  3Comments