Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to separate an integer into two numbers. Something like dividing by two but I only want integer components as a result, such as:

6 = 3 and 3
7 = 4 and 3

I tried the following, but I'm not sure its the best solution.

var number = 7;
var part1 = 0;
var part2 = 0;

if((number % 2) == 0) {
    part1 = number / 2;
    part2 = number / 2;
}
else {
    part1 = parseInt((number / 2) + 1);
    part2 = parseInt(number / 2);
}

This does what I want, but I don't think this code is clean.

Are there better ways of doing this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
427 views
Welcome To Ask or Share your Answers For Others

1 Answer

Just find the first part and subtract it from the original number.

var x = 7;

var p1 = Math.floor(x / 2);
var p2 = x - p1;

console.log(p1, p2);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...