Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Round to the nearest value on a scale

Lets say I have a scale with 10 values between a know min and max value. How can I get the nearest value on the scale for value between min and max. Example:

min = 0, max = 10, value = 2.75 -> expected: value = 3
min = 5, max = 6, value = 5.12 -> expected: value = 5.1
min = 0, max = 1, value = 0.06 -> expected: value = 0.1
like image 422
Andreas Köberle Avatar asked Feb 18 '23 08:02

Andreas Köberle


2 Answers

You could use something like this

function nearest(value, min, max, steps) {
  var zerone = Math.round((value - min) * steps / (max - min)) / steps; // bring to 0-1 range    
  zerone = Math.min(Math.max(zerone, 0), 1) // keep in range in case value is off limits
  return zerone * (max - min) + min;
}

console.log(nearest(2.75, 0, 10, 10)); // 3
console.log(nearest(5.12, 5, 6, 10)); // 5.1
console.log(nearest(0.06, 0, 1, 10)); // 0.1

Demo at http://jsfiddle.net/gaby/4RN37/1/

like image 103
Gabriele Petrioli Avatar answered Feb 28 '23 17:02

Gabriele Petrioli


Your scenario doesn't make much sense to me. Why does .06 round to 1 and not .1 but 5.12 rounds to 5.1 with the same scale (1 integer)? It's confusing.

Either way, if you want to round to a precise # of decimal places, check this out: http://www.javascriptkit.com/javatutors/round.shtml

var original=28.453

1) //round "original" to two decimals
var result=Math.round(original*100)/100  //returns 28.45

2) // round "original" to 1 decimal
var result=Math.round(original*10)/10  //returns 28.5

3) //round 8.111111 to 3 decimals
var result=Math.round(8.111111*1000)/1000  //returns 8.111

With this tutorial, you should be able to do exactly what you want.

like image 37
Eli Gassert Avatar answered Feb 28 '23 17:02

Eli Gassert