Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb PHP - Integers with decimals

This is a follow up to another post i made about inserting an integer into mongodb. I have this working just fine by using the (int) but now when it inserts the number into the db is strips everything after the decimal. So if i had 154.65 it would be inserted into the mongodb as 154 with nothing after the decimal.

My question is how do i get this to keep all numbers after the decimal? Also if anyone has a link to these sting/numeric functions i'd appreciate a reference. Thanks.

$number["xyz"]    = (int) $_POST["number"] ;
$collection->insert($number);

This inserts it as a integer but strips everything after the decimal. I tried you suggestion

$number["xyz"]    = floatval($_POST["number"]) ;
$collection->insert($number);

but this still strips off everything after the decimal. My though it i need something that looks like this so that it is in mongo format:

$number["xyz"]    = (dec) $_POST["number"] ;
$collection->insert($number);
like image 918
user982853 Avatar asked Nov 22 '25 10:11

user982853


1 Answers

There is no natively supported decimal format. Your options are floating point (cast prior to saving it), integer (which results in the removal of decimals as you're seeing) or string (cast prior to saving it). The optimal choice depends on your functional requirements. For example, if it's a monetary value you do not want to use floats but store the value in cents as an integer (15465 in your example).

like image 129
Remon van Vliet Avatar answered Nov 24 '25 01:11

Remon van Vliet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!