Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

javascript - Separate an integer into two (nearly) equal parts

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

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

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...