0

I have to divide n number into 3 parts according to given rule but the divided number should not be a floating-point number if the given n is an odd number.

Example

`const rule = [50,30,20]` . // in percentagee

 const n = 10;

the expected result should // 5,3,2

but if the given number is an odd number then the output should be as given below

 n = 9 
 output 4,3,2

when getting the percentage according to rules it comes as follow

4.5,2.7,1.8

Now I want if the fractional part of the number is up to .5, the argument should be rounded to the next lower integer. If the fractional part of the number is greater than .5, the argument is rounded to the next higher integer.

This is NOT asking how to round floating point numbers, as the dupe target says. This is asking how to round DOWN .5 cases.

ANSWER: var result = -Math.round(-num);

Jitender
  • 7,593
  • 30
  • 104
  • 210
  • @NinaScholz `Math.round` will round 4.5 to 5 not to 4 per the post. – Ryan Wilson Aug 08 '19 at 18:32
  • @NinaScholz My first try was Math.round but that does fit into the requirement. I know it can be done in many ways like splitting number and then writing if and else condition. But I am looking for if there is any built-in feature to support this requirement – Jitender Aug 08 '19 at 18:38

1 Answers1

3

You can do this by negating both the result and the argument to Math.round.

E.g. var result = -Math.round(-num);

The only thing this changes is the .5 case, as -4.5 rounds up to -4, then you simply change the sign again.