Rounding numbers to 2 digits after comma

前端 未结 8 1191
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 12:14

I have no idea how to do this? I\'m adding comma numbers, result is of course always a number with way too many digits after the comma. anyone?

相关标签:
8条回答
  • 2020-11-28 13:11

    I use this:

    function round(value, precision) {
    
    	if(precision == 0)
    		return Math.round(value);  	
    
    	exp = 1;
    	for(i=0;i<precision;i++)
    		exp *= 10;
    
    	return Math.round(value*exp)/exp;
    }

    0 讨论(0)
  • 2020-11-28 13:15

    Though we have many answers here with plenty of useful suggestions, each of them still misses some steps.
    So here is a complete solution wrapped into small function:

    function roundToTwoDigitsAfterComma(floatNumber) {
        return parseFloat((Math.round(floatNumber * 100) / 100).toFixed(2));
    }
    

    Just in case you are interested how this works:

    1. Multiple with 100 and then do round to keep precision of 2 digits after comma
    2. Divide back into 100 and use toFixed(2) to keep 2 digits after comma and throw other unuseful part
    3. Convert it back to float by using parseFloat() function as toFixed(2) returns string instead

    Note: If you keep last 2 digits after comma because of working with monetary values, and doing financial calculations keep in mind that it's not a good idea and you'd better use integer values instead.

    0 讨论(0)
提交回复
热议问题