是否有一个JS函数来查找小数点前后的值

Is there ay JS function to find value before and after decimal point

本文关键字:小数点 查找 有一个 JS 函数 是否      更新时间:2023-09-26

我正在使用JavaScript验证一个十进制数。我只是用NaN

var a = 12345.67是否有任何javascript函数来获取小数点前后的计数或值本身?

before()  should return 1234
after() should return 67

请不要建议子字符串!

var a = 12345.67;
alert(a.toString().split(".")[0]); ///before
alert(a.toString().split(".")[1]); ///after

这是一个简单的小提琴http://jsfiddle.net/qWtSc/


zzzzBov的建议是

Number.prototype.before = function () {
  var value = parseInt(this.toString().split(".")[0], 10);//before
  return value ? value : 0;
}
Number.prototype.after = function () {
  var value = parseInt(this.toString().split(".")[1], 10);//after
  return value ? value : 0;
}
使用

alert(a.before()); ///before
alert(a.after()); ///after

before很容易。这只是一个四舍五入的运算。

var before = function(n) {
  return Math.floor(n);
};

after未经字符串处理更难。我是说你怎么处理after(Math.PI) ?你毕竟不能保存一个有无限位数的整数。

但是对于一些字符串处理,这很容易,只要知道它不会是精确的,因为浮点数学的奇迹。

var after = function(n) {
  var fraction = n.toString().split('.')[1];
  return parseInt(fraction, 10);
};

播放其他答案…你想要一个"数字"版本……将其转换为字符串并使用split函数仍然是最简单的…

function getNatural(num) {
    return parseFloat(num.toString().split(".")[0]);
}
function getDecimal(num) {
    return parseFloat(num.toString().split(".")[1]);
}
var a = 12345.67;
alert(getNatural(a)); ///before
alert(getDecimal(a)); ///after
http://jsfiddle.net/rlemon/qWtSc/1/

var decimalPlaces = 2;    
var num = 12345.673
var roundedDecimal = num.toFixed(decimalPlaces);
var intPart = Math.floor(roundedDecimal);
var fracPart = parseInt((roundedDecimal - intPart), 10);
//or
var fractPart = (roundedDecimal - intPart) * Math.pow(10, decimalPlaces);

查找点后字符的数目/长度:

var a = 12345.67;
var after_dot = (a.toString().split(".")[1]).length;
var before_dot= (a.toString().split(".")[0]).length;

不幸的是,没有办法使用数学函数以可靠的方式获得阶乘部分,因为经常会出现非常奇怪的四舍五入,这取决于所使用的Javascript引擎。最好的方法是将其转换为字符串,然后检查结果是十进制还是科学记数法。

Number.prototype.after = function() {
    var string = this.toString();
    var epos = string.indexOf("e");
    if (epos === -1) { // Decimal notation
        var i = string.indexOf(".");
        return i === -1 ? "" : n.substring(i + 1);
    }
    // Scientific notation
    var exp = string.substring(epos + 1) - 0; // this is actually faster
                                              // than parseInt in many browsers
    var mantix = n.string.substring(0, epos).replace(".", "");
    if (exp >= -1) return mantix.substring(exp + 1);
    for (; exp < -1; exp++) mantix = "0" + mantix;
    return mantix;
}

如果小数点后的数字是固定的,则此解决方案无需转换为字符串。

这个例子给出了十进制后2位数字的解。

小数点前

:

   const wholeNum = Math.floor(num);
小数后

:

   let decimal = (num - wholeNum) * 100