Round a number to Top 4023.8599999999997€

Asked

Viewed 596 times

5

I have 4023.8599999999997€ to round to 4023.86, tried:

Math.round(sum1) 

but the result was :4024€

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

How to do this I’m using Javascript.

  • 2

    I’ve never seen class Math nor point as method invocator in php

  • 1

    I think he wants something like this var valor = 4023.8599999999997;

console.log(Math.round(valor * 100)/100);

3 answers

9


PHP

<?php 

    $var = 4023.8599999999997;

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

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

    echo floor($var); // 4023

round() - Automatically round, makes the functions of the ceil and of 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

8

  • I’ll check this then the solution is to pass the jscript value to php? Obg

  • 1

    In everything you need to work with a decimal type or work with integers. In these questions linked has more information why this happens. And it occurs in all languages, simply is a "problem" of the processor. The solutions that seem to solve the problem only create an illusion. The accounts will be all wrong. I’ve seen company take a tax fine as a result of this.

  • in this case is nothing very serious but thank you for the tip!

  • 3

    How is it not serious?

  • It’s not very official, I was just calculating the estimated amount of payments, of course if it’s 100% better :)

  • 1

    If it’s better, then it matters. If it’s money, it matters. Even if they are estimates, are you saying that the whole system is correct and only the estimates were made wrong? Or has no one ever realized that the whole system is wrong? And that even if you’re right, if this value is used elsewhere, it contaminates everything. There’s no 99% right, or it’s 100% right or it’s 0% right.

  • yes :) anyway here for this I used it :(Math.round(sum1 * 100)/100) seems to solve the problem

  • 3

    Coincidence solutions are not solutions.

Show 3 more comments

7

I ran a test on round and worked ok:

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

4023.86

Ideone

Browser other questions tagged

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