Doubts in the PHP float function

Asked

Viewed 38 times

0

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

I have this float function where it turns a string into a float value, only it cuts the values. Example:

if "8.75" is entered the function converts to 8

where it was to convert in 8,75.

  • 1

    Actually this code is making a serious mistake and many programmers do not realize this: https://answall.com/q/104193/101 and https://answall.com/q/219211/101

1 answer

2


First, by answering your question:

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

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

For information on converting strings to float, see the section String to number conversion. For values of other types, the value is first converted to integer and then to float. See section 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’re doing is a parsing of the kind string for float, recommend you take a look at the links above, which are from the PHP documentation for better understanding.

You can do it like 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 thus:

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

Explaining:

A function has been created to treat the comma substitution, which is what is happening in your case (because the float uses the point for separating decimal values).

Other examples:

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

output: float(1545.37)

Reference: PHP manual

Browser other questions tagged

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