Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

get nearest multiple of a number javascript

/*
	Gets the nearest multiple of a given number.
    
    @param {Number} number The number to go up from.
    @param {Number} multiple The base to get the multiple of.
*/
function getNearestMultiple(number, multiple)
{
	return number + (multiple - (number % multiple));
}

/* example code below (very repetitive, but you don't need to copy it) */

var num1 = 1;
var num2 = 4;
var num3 = 6;
var num4 = 8;
var num5 = 13;
var num6 = 12;
var num7 = 14;
var num8 = 19;
var num9 = 21;

console.log(`
Number: ${num1}
Base: 2
Next Multiple: ${getNearestMultiple(num1, 2)}`);
console.log(`
Number: ${num2}
Base: 3
Next Multiple: ${getNearestMultiple(num2, 3)}`);
console.log(`
Number: ${num3}
Base: 4
Next Multiple: ${getNearestMultiple(num3, 4)}`);
console.log(`
Number: ${num4}
Base: 5
Next Multiple: ${getNearestMultiple(num4, 5)}`);
console.log(`
Number: ${num5}
Base: 6
Next Multiple: ${getNearestMultiple(num5, 6)}`);
console.log(`
Number: ${num6}
Base: 7
Next Multiple: ${getNearestMultiple(num6, 7)}`);
console.log(`
Number: ${num7}
Base: 8
Next Multiple: ${getNearestMultiple(num7, 8)}`);
console.log(`
Number: ${num8}
Base: 9
Next Multiple: ${getNearestMultiple(num8, 9)}`);
console.log(`
Number: ${num9}
Base: 10
Next Multiple: ${getNearestMultiple(num9, 10)}`);

// output
/*
    Number: 1
    Base: 2
    Next Multiple: 2
	
    Number: 4
    Base: 3
    Next Multiple: 6
	
    Number: 6
    Base: 4
    Next Multiple: 8
	
    Number: 8
    Base: 5
    Next Multiple: 10
	
    Number: 13
    Base: 6
    Next Multiple: 18
	
    Number: 12
    Base: 7
    Next Multiple: 14
	
    Number: 14
    Base: 8
    Next Multiple: 16
	
    Number: 19
    Base: 9
    Next Multiple: 27
	
    Number: 21
    Base: 10
    Next Multiple: 30
*/
 
PREVIOUS NEXT
Tagged: #nearest #multiple #number #javascript
ADD COMMENT
Topic
Name
9+2 =