开发者

How to make 5509.099999999999 as 5509.09 using javascript

How to make 5509.099999999999 as 5509.09开发者_JAVA技巧 using javascript.


Lots of mathy options that end up with .1 so how about;

var f = 5509.099999999999

if ((f = f.toString()).indexOf(".") >= 0)
    f = f.substr(0, 3 + f.indexOf("."))

print(parseFloat(f))

>>5509.09


Have you tried this?

var value = 5509.099999999999;
var str = value.toString();
var result = str.substr(0,7);

Then if you need it to be a float again you can do:

var FinalAnswer = parseFloat(result);

You don't need all these variables, but that is the step by step.


   var result = (Math.round((5509.09999 * 100) - 1)) / 100;


You could use .toFixed(2) but this will round the value, so in your example you'll end up with 5509.10 instead of 5509.09.

The next best option is to use Math.floor(), which truncates rather than rounding. Unfortunately, this only gives integer results, so to get the result to 2 decimal places, you'd need to multiply by 100, then use Math.floor(), and then divide by 100 again.

var value = 5509.099999999999;
var result = Math.floor(value*100)/100;

[EDIT] Hmm, unfortunately, the above doesn't work due to problems with floating point precision -- even just the first step of multiplying it by 100 gives 550910.

Which means that the best answer is likely to be converting it to a string and chopping the string into bits.

var value = 5509.099999999999;
var str_value = value.toString();
var bits = str_value.split('.');
var result = bits[0]+"."+bits[1].substr(0,2);

I wouldn't normally suggest doing string manipulation for this sort of thing, because it is obviously a maths problem, but given the specific requirements of the question, it does seem that this is the only workable solution in this case.


You can truncate the number to a certain number of decimal places using this function:

function truncateNumber(number, digits){
 var divisor = Math.pow(10,digits);
 return Math.floor(number*divisor)/divisor;
}

If you want to round the number instead, you can use JavaScript's built in Number.toFixed function. If you always want the number a certain number of digits long, you can use the Number.toPrecision function.


if you want to take two decimal places, you can use .toPrecision(n) javascript function, where n is the total number of digits desired.

so, for your example, you'd have to do

var x = 5509.099999999999;
x = x.toPrecision(6);

this, however, rounds results in 5509.10

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜