Formatting a number with exactly two decimals in JavaScript

后端 未结 30 2222
广开言路
广开言路 2020-11-21 06:29

I have this line of code which rounds my numbers to two decimal places. But I get numbers like this: 10.8, 2.4, etc. These are not my idea of two decimal places so how I can

30条回答
  •  [愿得一人]
    2020-11-21 06:49

    I'm fix the problem the modifier. Support 2 decimal only.

    $(function(){
      //input number only.
      convertNumberFloatZero(22); // output : 22.00
      convertNumberFloatZero(22.5); // output : 22.50
      convertNumberFloatZero(22.55); // output : 22.55
      convertNumberFloatZero(22.556); // output : 22.56
      convertNumberFloatZero(22.555); // output : 22.55
      convertNumberFloatZero(22.5541); // output : 22.54
      convertNumberFloatZero(22222.5541); // output : 22,222.54
    
      function convertNumberFloatZero(number){
    	if(!$.isNumeric(number)){
    		return 'NaN';
    	}
    	var numberFloat = number.toFixed(3);
    	var splitNumber = numberFloat.split(".");
    	var cNumberFloat = number.toFixed(2);
    	var cNsplitNumber = cNumberFloat.split(".");
    	var lastChar = splitNumber[1].substr(splitNumber[1].length - 1);
    	if(lastChar > 0 && lastChar < 5){
    		cNsplitNumber[1]--;
    	}
    	return Number(splitNumber[0]).toLocaleString('en').concat('.').concat(cNsplitNumber[1]);
      };
    });

提交回复
热议问题