0

in my table, I have a decimal field of quantity. The value of 'quantity' in the database is 1.00 but when I selecting it from query, it is giving me integer 1. However, if the value will 1.25, it gives the same float value 1.25. Here is my query and output -

Query

$app_cart = $this->AppCart->find()->select(['AppCart.id','item'=>'Items.name','price'=>'Items.sales_rate','quantity'=>'AppCart.quantity'])
        ->where(['AppCart.user_id'=>1])->contain(['Items']);

Output

{
"success": true,
"message": "List Found",
"app_cart": [
    {
        "id": 4,
        "item": "KANGAN SAREE",
        "price": 1375,
        "quantity": 1
    },
    {
        "id": 5,
        "item": "KANGAN SAREE",
        "price": 1375,
        "quantity": 1
    }
]}

I have tried

$app_cart
        ->selectTypeMap()
        ->addDefaults([
            'quantity' => 'decimal'
        ]);
26vivek
  • 191
  • 1
  • 2
  • 9
  • 3
    It's not reading it as an integer, it's just displaying that way. Pretty normal behaviour for PHP; `print 1.00` and `print (float)1.00` will display simply `1`. If you have 1.20 in your database, it'll show as 1.2. This is obviously machine-readable output you're generating here, is there a problem with the recipient handling it incorrectly? Or you're just debugging and thinking that something might be wrong because it's not showing all the decimals? – Greg Schmidt Oct 20 '18 at 05:25
  • you can fix it on DB level `select format(mycolumn, 2) from mytable;` [see](https://stackoverflow.com/questions/15578410/mysql-is-cutting-00-in-decimals) – amar9312 Oct 20 '18 at 05:28
  • @tphobe9312 how to implement DB level in cakephp query? – 26vivek Oct 20 '18 at 06:23
  • @GregSchmidt so there is no way to get 1.00 in output? – 26vivek Oct 20 '18 at 06:24
  • I meant to say just use `format` function in select method – amar9312 Oct 20 '18 at 07:22
  • I would use the `Number` helper in the view. – GreyRoofPigeon Oct 20 '18 at 14:46
  • 1
    There are various ways to get 1.00 in the output. I was asking whether you truly need to get 1.00 in this output; what you've shown seems like the sort of thing where you wouldn't necessarily need it, and doing extra work for no reason is never a good idea. Maybe this is an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)? – Greg Schmidt Oct 20 '18 at 16:14
  • @GregSchmidt actually I am making API for Android. The Android team needs if the value will decimal at any point of time so all value should come in decimal. – 26vivek Oct 21 '18 at 05:42
  • @LinkinTED I can't use number format because i have to send it in API – 26vivek Oct 21 '18 at 05:43
  • 1
    The android app will have to validate/parse/cast the value anyways, so why bother with this if the rule is "_field x must be a decimal_"? Trailing zero's should be totally irrelevant in that situation. – ndm Oct 21 '18 at 14:52

0 Answers0