使用JavaScript获取数字的小数部分

361

我有像 3.21.6 这样的浮点数。

我需要将这个数字分离成整数和小数两部分。例如,值为 3.2 的数字将被拆分为两个数字,即 30.2

获取整数部分很容易:

n = Math.floor(n);

但是我在获取小数部分时遇到了问题。 我尝试过这个:

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

但它并不总是正确的工作。

先前的代码产生以下输出:

n = 3.1 // gives remainder = 1.1

我这里缺少了什么?


2
请注意,n = Math.floor(n); 仅适用于非负数,以返回您所需的结果(整数部分)。 - tsemer
请使用“%1”而不是“%2”来简化操作。 - masterxilo
4
decimalPart = number - Math.floor(number) 可以翻译为:小数部分等于数字减去向下取整后的结果。此外,你可以增加精度。parseFloat(decimalPart.toPrecision(3))表示保留 3 位小数的浮点数。 - Abhishek Chandel
要获取浮点数的整数部分,请使用Math.trunc(),而不是Math.floor()。 - undefined
33个回答

1
虽然我回答已经很晚了,请看一下代码。
let floatValue = 3.267848;
let decimalDigits = floatValue.toString().split('.')[1];
let decimalPlaces = decimalDigits.length;
let decimalDivider = Math.pow(10, decimalPlaces);
let fractionValue = decimalDigits/decimalDivider;
let integerValue = floatValue - fractionValue;

console.log("Float value: "+floatValue);
console.log("Integer value: "+integerValue);
console.log("Fraction value: "+fractionValue)

1
使用逗号作为小数点分隔符会导致失败。 - vanowm

1

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://dev59.com/J1kT5IYBdhLWcg3wXubP
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


1

我喜欢这个答案 https://dev59.com/mG855IYBdhLWcg3wJQvT#4512317,只需要应用浮点修复即可。

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

顺便说一句,如果您是加密货币交易平台开发人员、银行系统开发人员或任何JS开发人员 ;) 请在所有地方应用fpFix。谢谢!


0

看了几个之后,我现在正在使用...

var rtnValue = Number(7.23);
var tempDec = ((rtnValue / 1) - Math.floor(rtnValue)).toFixed(2);

抱歉,但 Number(7.23) 的意义是什么? 7.23 已经是一个数字了。而且为什么要除以1? - General Grievance

0
例如,对于两个数字相加的情况。
function add(number1, number2) {
let decimal1 = String(number1).substring(String(number1).indexOf(".") + 1).length;
let decimal2 = String(number2).substring(String(number2).indexOf(".") + 1).length;

let z = Math.max(decimal1, decimal2);
return (number1 * Math.pow(10, z) + number2 * Math.pow(10, z)) / Math.pow(10, z);
}

0

这个函数将浮点数拆分为整数并以数组形式返回:

function splitNumber(num)
{
  num = (""+num).match(/^(-?[0-9]+)([,.][0-9]+)?/)||[];
  return [ ~~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(如果不存在数字):

function splitNumber(num)
{
  num = (""+num).match(/^(-?[0-9]+)([,.][0-9]+)?/);
  return [ 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,  null ]
console.log(splitNumber(-2.7));    // [ -2,   0.7 ]
console.log(splitNumber("test"));  // [ null, null ]


1
不适用于“console.log(splitNumber(3.02));”,当第一个小数位为零时! - Cesar Devesa
我发布了一个高效的函数答案,你能否测试一下? - Cesar Devesa

0

您也可以截断数字

function decimals(val) {
    const valStr = val.toString();
    const valTruncLength = String(Math.trunc(val)).length;

    const dec =
        valStr.length != valTruncLength
            ? valStr.substring(valTruncLength + 1)
            : "";

    return dec;
}

console.log("decimals: ", decimals(123.654321));
console.log("no decimals: ", decimals(123));


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

function splitNum(num) {
  num = num.toString().split('.')
  num[0] = Number(num[0])
  if (num[1]) num[1] = Number('0.' + num[1])
  else num[1] = 0
  return num
}
//call this function like this
let num = splitNum(3.2)
console.log(`Integer part is ${num[0]}`)
console.log(`Decimal part is ${num[1]}`)
//or you can call it like this
let [int, deci] = splitNum(3.2)
console.log('Intiger part is ' + int)
console.log('Decimal part is ' + deci)


0

阅读并检查所有答案,我认为分享另一种实现“在js中获取小数部分的方法”是一个好主意:

const fractionCount = (number)=>{
    let count = 0;
    while(number !== Math.floor(number)){
        number*=10;
        count++;        
    }
    return count;    
}

console.log(fractionCount(2.3456790))


0

还有另一种方式:

function fract(x) {
  return 1 - (Math.ceil(x) - x);
}

fract(2.3) // <-- 0.2999999999999998

1
不适用于负数。 - General Grievance

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接