Doubts in the PHP float function

0
$valorBaixa  = (float)$this->input->post('valorBaixa');

I have this float function where the same one transform a string in float value, only that it is cutting the values. Example:

If you enter "8.75" the function converts to 8

where it was to convert to 8.75.

    
asked by anonymous 04.12.2018 / 20:58

1 answer

2

First, answering your question:

Floating-point numbers (also known as floats, doubles, or real numbers) can be specified using any of the following syntax:

<?php
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
?>
  

For information on converting strings to float, see the Conversion of Strings to Numbers . For values of other types, the value is first converted to integer and then to float. See Converting to integers for more information. In PHP 5, a warning is issued if you try to convert an object to a float.

Reference: PHP manual .

What you are doing is parsing of type string to float , I recommend you take a look at the links above, which are from the PHP documentation for better understanding.

You can do this:

<?php

function tofloat($num) {
    $dotPos = strrpos($num, '.');
    $commaPos = strrpos($num, ',');
    $sep = (($dotPos > $commaPos) && $dotPos) ? $dotPos : 
        ((($commaPos > $dotPos) && $commaPos) ? $commaPos : false);

    if (!$sep) {
        return floatval(preg_replace("/[^0-9]/", "", $num));
    } 

    return floatval(
        preg_replace("/[^0-9]/", "", substr($num, 0, $sep)) . '.' .
        preg_replace("/[^0-9]/", "", substr($num, $sep+1, strlen($num)))
    );
}

And use it like this:

$valorBaixa = tofloat($this->input->post('valorBaixa'));

Explaining:

A function has been created to handle the replacement of the comma, which is what is happening in your case (because the float uses the decimal point separator).

Other examples:

$numero = 'R$ 1.545,37';
var_dump(tofloat($numero)); 

output: float(1545.37)

Reference: PHP manual

    
04.12.2018 / 21:05