js arrotondare numeri code example

Example 1: js arrotondare superiore numero

// value is the value to round
 // places if positive the number of decimal places to round to
 // places if negative the number of digits to round to
 function roundTo(value, places){
     var power = Math.pow(10, places);
     return Math.round(value * power) / power;
 }
 var myNum = 10000/3;    // 3333.3333333333335
 roundTo(myNum, 2);  // 3333.33
 roundTo(myNum, 0);  // 3333
 roundTo(myNum, -2); // 3300

Example 2: js arrotondare superiore numero

function ceilTo(value, places){
     var power = Math.pow(10, places);
     return Math.ceil(value * power) / power;
 }
 function floorTo(value, places){
     var power = Math.pow(10, places);
     return Math.floor(value * power) / power;
 }

Example 3: js arrotondare numeri

var a = Math.round(2.3);       // a is now 2  
var b = Math.round(2.7);       // b is now 3
var c = Math.round(2.5);       // c is now 3

var a = Math.ceil(2.3);        // a is now 3
var b = Math.ceil(2.7);        // b is now 3

Input  : Math.floor(5.78)
Output : 5

Input  : Math.floor(1.5)
Output : 1