我有像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

我错过了什么?


当前回答

一个简单的方法是:

Var x = 3.2; var decimal = x - Math.floor(x); console.log(小数);/ /返回0.20000000000000018

不幸的是,这并没有返回准确的值。然而,这很容易解决:

Var x = 3.2; var decimal = x - Math.floor(x); console.log (decimals.toFixed (1));/ /返回0.2

如果你不知道小数位数,你可以用这个:

Var x = 3.2; var decimal = x - Math.floor(x); var decimalPlaces = x.toString().split('.')[1].length; decimals = decimal . tofixed (decimalPlaces); console.log(小数);/ /返回0.2

其他回答

一个不错的选择是将数字转换为字符串,然后分割它。

// Decimal number
let number = 3.2;

// Convert it into a string
let string = number.toString();

// Split the dot
let array = string.split('.');

// Get both numbers
// The '+' sign transforms the string into a number again
let firstNumber  = +array[0]; // 3
let secondNumber = +array[1]; // 2

在一行代码中

let [firstNumber, secondNumber] = [+number.toString().split('.')[0], +number.toString().split('.')[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 a = 10.2
var c = a.toString().split(".")
console.log(c[1] == 2) //True
console.log(c[1] === 2)  //False

但这比布莱恩·m·亨特提出的解决方案需要更长的时间

(2.3 % 1).toFixed(4)

我喜欢这个答案https://stackoverflow.com/a/4512317/1818723只需要应用浮点修正

function fpFix(n) {
  return Math.round(n * 100000000) / 100000000;
}

let decimalPart = 2.3 % 1; //0.2999999999999998
let correct = fpFix(decimalPart); //0.3

完成负极和正极处理功能

function getDecimalPart(decNum) {
  return Math.round((decNum % 1) * 100000000) / 100000000;
}

console.log(getDecimalPart(2.3)); // 0.3
console.log(getDecimalPart(-2.3)); // -0.3
console.log(getDecimalPart(2.17247436)); // 0.17247436

P.S.如果你是加密货币交易平台开发人员或银行系统开发人员或任何JS开发人员;)请在任何地方应用fpFix。谢谢!

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