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

Categories

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

javascript - Math.ceil not working with negative floats

I am trying to create a RoundUp function with help of Math.ceil it working fine with positive number but do not round up the negative numbers Here is what i am trying

var value = -12.369754; --> output = -12
// make value = 12.369754; and out put will be 13
var decimalPoints = 0;

if (decimalPoints == 0) {
                value = Math.ceil(parseFloat(value));
            }
console.log(value);

Here is the Fiddle http://jsfiddle.net/n7ecyr7h/

Why This function? I need to create a function in which user will give a number and decimal points upto which he wants to round the number The RoundUp function will roundUp the given value to a given number of decimal points For example if user enters 12.12445 and wants to roundUp to 3 decimal points the output will be 12.125 Here is a table of required outputs with 2 decimal points

**Input**              **output**

1.2369                   1.24

1.2869                   1.29

-1.1234                  -1.13

-1.17321                 -1.18

And here is the Updated Fiddle with original JS code http://jsfiddle.net/n7ecyr7h/1/

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The Math.ceil method does actually round up even for negative values. The value -12 is the closest integer value that is at higher than -12.369754.

What you are looking for is to round away from zero:

value = value >= 0 ? Math.ceil(value) : Math.floor(value);

Edit:

To use that with different number of decimal points:

// it seems that the value is actually a string
// judging from the parseFloat calls that you have
var value = '-12.369754';
var decimalPoints = 0;

// parse it once
value = parseFloat(value);

// calculate multiplier
var m = Math.pow(10, decimalPoints);

// round the value    
value = (value >= 0 ? Math.ceil(value * m) : Math.floor(value * m)) / m;

console.log(value);

Demo: http://jsfiddle.net/Guffa/n7ecyr7h/3/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...