TransWikia.com

Is there function to perform calculation on decimal column value of mongodb in PHP

Stack Overflow Asked by omprakash sharma on September 15, 2020

I have to calculate the total discount percentage(%) of the Item based on Item price and Item sales price.

But column data store in mongodb collection in decimal formate like 11,000

so when performing calculation as

$itemPrice = 10,000;
$itemSalesPrice = 11,000;

$discount = (($itemPrice - $itemSalesPriceprice) / $itemPrice) * 100;

PHP returns Error as

A non well formed numeric value encountered
Blockquote

I have tried to use implicit conversion to float but value retains is till comma.
Like

var_dump((float)$itemPrice);

The output is

10

2 Answers


function toFloat($numeric):float
{
 return (float)str_replace(',','',$numeric);
}


$itemPrice =toInt("10,000");
$itemSalesPrice = toInt("11,000");

$discount = (($itemPrice - $itemSalesPriceprice) / $itemPrice) * 100;

Answered by dılo sürücü on September 15, 2020

If there is no way to change the data stored in database, you could just do a str_replace like this.

$itemPriceFromDB = '10,000'; // get value from database as string
$itemSalesPriceFromDB = '11,000'; // get value from database as string

$itemPrice = (float) str_replace(',', '.', $itemPriceFromDB );
$itemSalesPrice= (float) str_replace(',', '.', $itemSalesPriceFromDB );

$discount = (($itemPrice - $itemSalesPrice) / $itemPrice) * 100;

Answered by shock_gone_wild on September 15, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP