Home > Web Front-end > JS Tutorial > body text

JavaScript保留两位小数的2个自定义函数_javascript技巧

WBOY
Release: 2016-05-16 16:49:54
Original
1164 people have browsed it

对于一些小数点后有多位的浮点数,我们可能只需要保留2位,但js没有提供这样直接的函数,所以我们得自己写函数实现这个功能,代码如下:

复制代码 代码如下:

function changeTwoDecimal(x) {
    var f_x = parseFloat(x);
    if (isNaN(f_x)) {
        alert('function:changeTwoDecimal->parameter error');
        return false;
    }
    var f_x = Math.round(x * 100) / 100;
    return f_x;
}

功能:将浮点数四舍五入,取小数点后2位用法:changeTwoDecimal(3.1415926)返回3.14 changeTwoDecimal(3.1475926)返回3.15


js保留2位小数(强制)

对于小数点位数大于2位的,用上面的函数没问题,但是如果小于2位的,比如:changeTwoDecimal(3.1),将返回3.1,如果你一定需要3.10这样的格式,那么需要下面的这个函数:

复制代码 代码如下:

function changeTwoDecimal_f(x) {
    var f_x = parseFloat(x);
    if (isNaN(f_x)) {
        alert('function:changeTwoDecimal->parameter error');
        return false;
    }
    var f_x = Math.round(x * 100) / 100;
    var s_x = f_x.toString();
    var pos_decimal = s_x.indexOf('.');
    if (pos_decimal         pos_decimal = s_x.length;
        s_x += '.';
    }
    while (s_x.length         s_x += '0';
    }
    return s_x;
}

功能:将浮点数四舍五入,取小数点后2位,如果不足2位则补0,
这个函数返回的是字符串的格式用法:changeTwoDecimal(3.1415926)返回3.14 changeTwoDecimal(3.1)返回3.10
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!