How to do an exact/precise split or subtraction in PHP

Asked

Viewed 439 times

0

I’m having trouble making an exact calculation in PHP, note.

$selic = 0,96;
$ipca  = 0,42;
bcscale(10);
$sub = bcsub($selic, $ipca);   //Retona: 0.54000000
// ou
$sub = $selic - $ipca;         //Retorna: 0.54

The exact result for this formula no Excel is: 0,54316901573592300

That goes for subtraction, addition, division and multiplication, someone can help me?

Editing
It was bad there, the error is in Excel, not with PHP. I’m not even a little used to it. But thank you all.

  • 1

    The problem is in the $selic and in the $ipca, Holy balls,0.96 - 0.46 of exactly 0.54

  • 4

    look friend 0,96 - 0,42 = 0,54 your formula in excel must be wrong

  • See in your excel file, that the value of ipca and Selic is not exactly these, extend the squares after the comma :)

  • I’m going to take this dynamic data from uam API, and this api only returns 2 homes after the comma

  • There’s nothing to do, unfortunately

  • 2

    $selic = 0.96013899947120500. $ipca = 0.41696998373528200 . result of subtraction: 0.54316901573592300. Now 0.96 - 0.46 = 0.54

  • So my problem will be with the API or with EXCEL? Which one should I trust?

  • Or look for a Ws that tells the value with more decimals, if you want to beat excel with the result in your calculation

  • Ixi, now where I’m gonna find a central bank WS, this one I got from portal de dados abertos do brasil

  • @bfavaretto The boy’s excel: https://onedrive.live.com/edit.aspx?cid=998af8ca813c01c8&page=view&resid=998AF8CA813C01C8! 176&parId=998AF8CA813C01C8! 175&authkey=! Aa3v8eddxxifbzo&app=Excel

Show 5 more comments

1 answer

3


Correcting your example, php will not interpret these "commas" have to be point, and it has to be in quotes if you are going to use string transformation, or without quotation marks if it is numeric, but even you have to exchange comma for point.

<?php
$selic = "0.96";
$ipca  = "0.42";
bcscale(10);
echo bcsub($selic, $ipca);   //Retona: 0.54000000
echo "<br>";// ou
echo ($selic - $ipca);         //Retorna: 0.54


$selic = "0.96013899947120500";
$ipca  = "0.41696998373528200";
bcscale(10);
echo bcsub($selic, $ipca,17);   //Retona: 0.54316901573592300
echo "<br>";// ou
echo ($selic - $ipca);         //Retorna: 0.54316901573592

Updated as comments

  • I know, it was my mistake, I didn’t copy this code I did just now, this data (ipca and Selic) I’ll take from an API, and it only has 2 houses after the comma understand? I wanted to be as precise in the formulas as possible!

  • 3

    Good ta explained that you have no problem in PHP, this part this right as example just pass a third parameter in bcsub(), will have to process the input data before doing the calculation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.