我有像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
我错过了什么?
我有像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
我错过了什么?
当前回答
这个函数将浮点数拆分为整数,并以数组形式返回:
函数拆分数(数) { num = (“”+num).match(/^(-?[0-9]+)([,.][0-9]+)?/)||[]; 返回 [ ~~num[1], +(0+num[2])||0 ]; } console.log(splitNumber(3.02)); [ 3, 0.2 ] console.log(splitNumber(123.456));[ 123, 0.456 ] console.log(splitNumber(789)); [ 789, 0 ] console.log(splitNumber(-2.7)); [ -2, 0.7 ] console.log(splitNumber(“test”)); [ 0, 0 ]
你可以将它扩展为只返回现有的数字,如果不存在数字则返回null:
函数拆分数(数) { num = (“”+num).match(/^(-?[0-9]+)([,.][0-9]+)?/); 返回 [ num ? ~~num[1] : null, num && num[2] ? +(0 + num[2]) : null ]; } console.log(splitNumber(3.02)); [ 3, 0.02 ] console.log(splitNumber(123.456));[ 123, 0.456 ] console.log(splitNumber(789)); [ 789 空 ] console.log(splitNumber(-2.7)); [ -2, 0.7 ] console.log(splitNumber(“test”)); [ 空,空 ]
其他回答
一个简单的方法是:
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
如果精度很重要,并且您需要一致的结果,这里有一些命题,它们将以字符串形式返回任何数字的小数部分,包括前导的“0.”。如果你需要它作为一个浮点数,只需在最后添加var f = parseFloat(result)。
如果小数部分等于零,则返回"0.0"。不测试Null, NaN和未定义的数字。
1. String.split
var nstring = (n + ""),
narray = nstring.split("."),
result = "0." + ( narray.length > 1 ? narray[1] : "0" );
2. String.substring, String.indexOf
var nstring = (n + ""),
nindex = nstring.indexOf("."),
result = "0." + (nindex > -1 ? nstring.substring(nindex + 1) : "0");
3. Math.floor, Number.toFixed, String.indexOf
var nstring = (n + ""),
nindex = nstring.indexOf("."),
result = ( nindex > -1 ? (n - Math.floor(n)).toFixed(nstring.length - nindex - 1) : "0.0");
4. Math.floor, Number.toFixed, String.split
var nstring = (n + ""),
narray = nstring.split("."),
result = (narray.length > 1 ? (n - Math.floor(n)).toFixed(narray[1].length) : "0.0");
这是一个jsPerf链接:https://jsperf.com/decpart-of-number/
我们可以看到,命题2是最快的。
这个函数将浮点数拆分为整数,并以数组形式返回:
函数拆分数(数) { num = (“”+num).match(/^(-?[0-9]+)([,.][0-9]+)?/)||[]; 返回 [ ~~num[1], +(0+num[2])||0 ]; } console.log(splitNumber(3.02)); [ 3, 0.2 ] console.log(splitNumber(123.456));[ 123, 0.456 ] console.log(splitNumber(789)); [ 789, 0 ] console.log(splitNumber(-2.7)); [ -2, 0.7 ] console.log(splitNumber(“test”)); [ 0, 0 ]
你可以将它扩展为只返回现有的数字,如果不存在数字则返回null:
函数拆分数(数) { num = (“”+num).match(/^(-?[0-9]+)([,.][0-9]+)?/); 返回 [ num ? ~~num[1] : null, num && num[2] ? +(0 + num[2]) : null ]; } console.log(splitNumber(3.02)); [ 3, 0.02 ] console.log(splitNumber(123.456));[ 123, 0.456 ] console.log(splitNumber(789)); [ 789 空 ] console.log(splitNumber(-2.7)); [ -2, 0.7 ] console.log(splitNumber(“test”)); [ 空,空 ]
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
你可以将其转换为字符串,并使用replace方法将整数部分替换为零,然后将结果转换回一个数字:
var number = 123.123812,
decimals = +number.toString().replace(/^[^\.]+/,'0');