Round a number to the tenth 4023.8599999999997 €

4

I have 4023.8599999999997 € to round to 4023.86, I tried:

Math.round(sum1) 

but the result was: 4024 €

I also tried Math.round(sum1,2) but did not.

How to do this I'm using JavaScript.

    
asked by anonymous 28.01.2016 / 12:30

3 answers

7

PHP

<?php 

    $var = 4023.8599999999997;

    echo round($var, 2).'<br>'; // 4023.86

    echo ceil($var).'<br>'; // 4024

    echo floor($var); // 4023

round() - Rounds automatically, performs the functions of ceil and floor .

ceil() - Round up, ignoring decimal places

floor() - Round down, ignoring decimal places

JS

var num = 4023.8599999999997;

Math.round(num); // 4024

num.toFixed(2); // 4023.86
    
28.01.2016 / 12:40
8

In fact, the only way to actually fix the problem is to change the type of data you are working on. You do not work with floating-point values with money. This is a serious mistake. Other solutions only mask the problems, ie throw the problem down the carpet. It can cause huge financial loss. See more at Different numbers become equal after conversion with doubleval and How to represent money in JavaScript?

    
28.01.2016 / 12:47
4

I tested with round and it worked ok:

$sum1 = 4023.8599999999997;
echo round($sum1, 2);
  

4023.86

Ideone

    
28.01.2016 / 12:35