how to divide a number a in a series of all whole numbers?

我的梦境 提交于 2019-12-11 11:40:47

问题


Hi sorry for asking this if this is a stupid question.

I would like to ask how to securely divide a number in Javascript that it will always output the result in a way that it will output pure whole numbers.

example:

10 / 2 ---> 5, 5 ( it would be 2 fives so it is whole number )

BUT

10 / 3 ---> 3, 3, 4 ( it would have two 3 and one 4 so that it would still result to 10 )


回答1:


10/3 will give you 3.333333..., never four... if you want to check is a number will give you "whole numbers" as you say, use modulo (%).

Modulo finds the remainder of division of one number by another.

For example

10%5 = 0 because 10 divided by 5 is a "whole number"

10%3 = 1 because the closest 10/3 is 3... 3x3=9... 10-9=1

So in your code, if you want to know if a number divided by another number is whole, you need to do

if (number1%number2 == 0) { ... }

Read more about it here

EDIT :

I read your question again and I think this fiddle is what you want

var number1 = 10,
    number2 = 3;

if (number1 / number2 == 0) {
    alert('the numbers are whole');
} else {
    var remainder = number1%number2;
    var wholes = Math.floor(number1 / number2);

    var output = '';

    for (var i = 0; i < (wholes - 1); i++) {
     output+= number2 + ', ';
    }

    output += (number2 + remainder);

    alert(output);
}



回答2:


Whatever your result is,just pass it through the parseInt function,For Eg:-

Suppose your answer is 4.3,

The whole number close to it will can be accounted using,

parseInt(4.3) Which equals 4.




回答3:


Another posibility: make the number a string and walk all the elements

var a = 11 / 4;
//turn it into a string and remove all non-numeric chars
a = a.toString().replace(/\D/g, '');
//split the string in seperate characters
a = a.split("");
var num = new Array();
//convert back to numbers
for (var i = 0; i < a.length; i++) {
    num.push(parseFloat(a[i]));
}
alert(num);

On a sidenote, you'll have to do some kind of rounding, to prevent eternally repeating numbers, like 10/3.

Here is a fiddle




回答4:


Look at this very simple example:

var x = 10;
var y = 3;

var result = x/y;
var rest = x%y;

for (var i=0; i<y; i++) {

    var output;

    if(i==y-1){
        output = parseInt(result + rest);
    }
    else{
        output = parseInt(result);
    }

    alert(output);
}

http://jsfiddle.net/guinatal/469Vv/4/



来源:https://stackoverflow.com/questions/23446086/how-to-divide-a-number-a-in-a-series-of-all-whole-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!