js 小数[非]四舍五入

1、四舍五入

(2.678).toFixed(2) // 2.68

 

2、不需要四舍五入

(parseInt(2.678*100)/100.0).toFixed(2) // 2.67

 

3、字节单位转换

function convertByte(bytesNum) {

            var unit = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB', 'BB', 'NB', 'DB'],
                count = 0;
                  
            if (bytesNum <= 0) {
                return bytesNum;
            }
            if (bytesNum < 1024) {
                return bytesNum + unit[0];
            }

            while (count<unit.length) {
                bytesNum = bytesNum / 1024;
                if (bytesNum < 1024) {
                    console.log(bytesNum);
                    bytesNum = bytesNum.toFixed(1) == parseInt(bytesNum.toFixed(1)) ? bytesNum.toFixed(0) : bytesNum.toFixed(1);//如果有小数则保留一位小数
                    return bytesNum + unit[count];
                }
                count++;
            }
        }

 

posted @ 2015-08-11 15:29  rdst  阅读(523)  评论(0编辑  收藏  举报