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.

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.