JSFiddle - React, Tailwind, and code Playground

by lamarant

HTML

<table>
    <thead>
       <tr>
           <th>value</th>
           <th>inprecise_round</th>
           <th>precise_round</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

CSS

th,td{ padding: 0 10px;}

JavaScript

function inprecise_round(value, decPlaces) {
  return Math.round(value*Math.pow(10,decPlaces))/Math.pow(10,decPlaces);
}

function precise_round(value, decPlaces){
    var val = value * Math.pow(10, decPlaces);
    var fraction = (Math.round((val-parseInt(val))*10)/10);

    //this line is for consistency with .NET Decimal.Round behavior
    // -342.055 => -342.06
    if(fraction == -0.5) fraction = -0.6;

    val = Math.round(parseInt(val) + fraction) / Math.pow(10, decPlaces);
    return val.toFixed(decPlaces);
}

function writeVal(val, precision)
{
    $('tbody').append('<tr><td>' + val + ' :: ' + precision + '</td><td>' + inprecise_round(val, precision) + '</td><td>' + precise_round (val, precision) + '</td></tr>');
}
writeVal(342.5555, 0)
writeVal(-342.55555, 0)
writeVal('1.2345678', 5);