0

I am working on a extremely simple API project and everything works the way its supposed to, until I use json_encode(). When I go to https://phoenix.ltda/api/index.php?version=1.3 it returns {"version":1.4000000000000001}. How would I remove the extra zeros and only get 1.4? This problem only occurs when I use json_decode(). How would I fix this? Would I use PHP's round()?

index.php

<?php

if(isset($_GET['version'])){
    $current_version = $_GET['version'];
    require_once 'includes/updates.php';
    $next_version = get_updated_version($current_version);
    $encode = array('version' => $next_version);
    $next_version = json_encode($encode);
    echo $next_version;
}

?>

updates.php

<?php

function get_updated_version($version){
    $string = $version+'.1';
    return $string;
}

?>

EDIT: Problem also occurs when I pass numbers such as 1.6 and 1.1.

Neutron
  • 1
  • 3
  • do `json_encode(array('version' => (string)$next_version))` https://3v4l.org/T4OAh or fix precision, is a dupe of https://stackoverflow.com/questions/42981409/php7-1-json-encode-float-issue – Lawrence Cherone Oct 12 '20 at 15:42

1 Answers1

0

Use round() to get rid of excess digits.

function get_updated_version($version){
    $string = round($version + .1, 3);
    return $string;
}

This will have at most 3 digits after the decimal point.

See Is floating point math broken? for the root cause.

Barmar
  • 741,623
  • 53
  • 500
  • 612