我有像3.2和1.6这样的浮点数。

我需要把这个数分成整数部分和小数部分。例如,3.2的值将被分成两个数字,即3和0.2

获取整数部分很简单:

n = Math.floor(n);

但是我在计算小数部分时遇到了麻烦。 我试过了:

remainder = n % 2; //obtem a parte decimal do rating

但它并不总是正确工作。

前面的代码有以下输出:

n = 3.1 // gives remainder = 1.1

我错过了什么?


当前回答

您可以使用parseInt()函数来获取整数部分,而不是使用它来提取小数部分

var myNumber = 3.2;
var integerPart = parseInt(myNumber);
var decimalPart = myNumber - integerPart;

或者你可以像这样使用正则表达式:

splitFloat = function(n){
   const regex = /(\d*)[.,]{1}(\d*)/;
   var m;

   if ((m = regex.exec(n.toString())) !== null) {
       return {
          integer:parseInt(m[1]),
          decimal:parseFloat(`0.${m[2]}`)
       }
   }
}

其他回答

以下工作不考虑十进制分隔符的区域设置…在此条件下,仅使用一个字符作为分隔符。

var n = 2015.15;
var integer = Math.floor(n).toString();
var strungNumber = n.toString();
if (integer.length === strungNumber.length)
  return "0";
return strungNumber.substring(integer.length + 1);

虽然不漂亮,但很准确。

下面的函数将返回一个包含2个元素的数组。第一个元素是整数部分,第二个元素是小数部分。

函数splitNum(num) { num = num. tostring ().split('.') num[0] = Number(num[0]) if (num[1]) num[1] = Number('0. ')' + num[1]) 否则num[1] = 0 返回num } //像这样调用这个函数 let num = splitNum(3.2) console.log('整数部分是${num[0]} ') console.log('小数部分为${num[1]} ') //或者你可以这样调用它 let [int, deci] = splitNum(3.2) console.log(' int部分是' + int) console.log('小数部分是' + deci)

以下是我的做法,我认为这是最直接的方法:

var x = 3.2;
int_part = Math.trunc(x); // returns 3
float_part = Number((x-int_part).toFixed(2)); // return 0.2

2021年更新

优化版本处理精度(或不)。

// Global variables. const DEFAULT_PRECISION = 16; const MAX_CACHED_PRECISION = 20; // Helper function to avoid numerical imprecision from Math.pow(10, x). const _pow10 = p => parseFloat(`1e+${p}`); // Cache precision coefficients, up to a precision of 20 decimal digits. const PRECISION_COEFS = new Array(MAX_CACHED_PRECISION); for (let i = 0; i !== MAX_CACHED_PRECISION; ++i) { PRECISION_COEFS[i] = _pow10(i); } // Function to get a power of 10 coefficient, // optimized for both speed and precision. const pow10 = p => PRECISION_COEFS[p] || _pow10(p); // Function to trunc a positive number, optimized for speed. // See: https://stackoverflow.com/questions/38702724/math-floor-vs-math-trunc-javascript const trunc = v => (v < 1e8 && ~~v) || Math.trunc(v); // Helper function to get the decimal part when the number is positive, // optimized for speed. // Note: caching 1 / c or 1e-precision still leads to numerical errors. // So we have to pay the price of the division by c. const _getDecimals = (v = 0, precision = DEFAULT_PRECISION) => { const c = pow10(precision); // Get precision coef. const i = trunc(v); // Get integer. const d = v - i; // Get decimal. return Math.round(d * c) / c; } // Augmenting Number proto. Number.prototype.getDecimals = function(precision) { return (isFinite(this) && (precision ? ( (this < 0 && -_getDecimals(-this, precision)) || _getDecimals(this, precision) ) : this % 1)) || 0; } // Independent function. const getDecimals = (input, precision) => (isFinite(input) && ( precision ? ( (this < 0 && -_getDecimals(-this, precision)) || _getDecimals(this, precision) ) : this % 1 )) || 0; // Tests: const test = (value, precision) => ( console.log(value, '|', precision, '-->', value.getDecimals(precision)) ); test(1.001 % 1); // --> 0.0009999999999998899 test(1.001 % 1, 16); // --> 0.000999999999999 test(1.001 % 1, 15); // --> 0.001 test(1.001 % 1, 3); // --> 0.001 test(1.001 % 1, 2); // --> 0 test(-1.001 % 1, 16); // --> -0.000999999999999 test(-1.001 % 1, 15); // --> -0.001 test(-1.001 % 1, 3); // --> -0.001 test(-1.001 % 1, 2); // --> 0

var decimal = n - Math.floor(n)

虽然这对负数不成立所以我们可能要这么做

n = Math.abs(n); // Change to positive
var decimal = n - Math.floor(n)