VLS
VLS

Reputation: 445

Subtraction of two numbers isn't stored in database

I have two numbers in my database which I want to subtract with intval() and bcdiv functions. I'm not sure why one of the numbers came as string the other one is float

This is var_dump of both numbers

number1: float(0.11037128) 
number2: string(10) "0.19902165"

Function which I'm trying to perform

$result = $number1 - $number2;

// var_dump($result) return float(-0.08865037)
$res->result = bcdiv(intval($number1 - $number2), 100000000, 8 ));

$res->save();

The column to which I want to store this result is DECIMAL(20,8).

There is no errors, nothing. Page is reload normally. Everything else got saved in database except this result.

I'm using Laravel framework and this is in my controller. Any ideas?

Upvotes: 0

Views: 166

Answers (2)

Vaibhavraj Roham
Vaibhavraj Roham

Reputation: 1165

If you are doing

$number1 =  0.11037128;
$number2 =  0.19902165;
$res->result = bcdiv(intval($number1 - $number2), 100000000, 8 ));

surely you are going to get 0.00000000 only.

As per the documentation of intval(), It picks the integer value from number. So after intval($number1 - $number2) you are going to get 0 hence you will get 0.00000000 as bcdiv() output.

Usecase I used

$number1 =  10.11037128; // Changed this number
$number2 =  0.19902165;
var_dump(bcdiv(intval($number1 - $number2), 100000000, 8 ));

which gives output as

string(10) "0.00000009"

Refer bcdiv docs and intval docs.

Edited

If you have issues with numbers like getting string type etc. then try to typecast them as below.

$number1 = (float) 10.11037128;
$number2 = (float) 0.19902165;

Upvotes: 1

Operands of bcdiv excluding "scale" must be strings Maybe it's a problem

http://php.net/manual/en/function.bcdiv.php

Upvotes: 1

Related Questions