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

我错过了什么?


当前回答

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

// 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]];

其他回答

数学函数更快,但总是返回不是本机的期望值。 我发现最简单的方法就是

(3.2+'').replace(/^[-\d]+\./, '')
float a=3.2;
int b=(int)a; // you'll get output b=3 here;
int c=(int)a-b; // you'll get c=.2 value here

语言独立方式:

var a = 3.2;
var fract = a * 10 % 10 /10; //0.2
var integr = a - fract; //3

注意,它只对分数长度为一个的数字正确)

浮点小数点符号和数字格式可以依赖于国家(.,),因此保留浮点部分的独立解为:

getFloatDecimalPortion = function(x) {
    x = Math.abs(parseFloat(x));
    let n = parseInt(x);
    return Number((x - n).toFixed(Math.abs((""+x).length - (""+n).length - 1)));
}

-它是国际化的解决方案,而不是位置依赖:

getFloatDecimalPortion = x => parseFloat("0." + ((x + "").split(".")[1]));

方案描述一步步:

parseFloat() for guaranteeing input cocrrection Math.abs() for avoiding problems with negative numbers n = parseInt(x) for getting decimal part x - n for substracting decimal part We have now number with zero decimal part, but JavaScript could give us additional floating part digits, which we do not want So, limit additional digits by calling toFixed() with count of digits in floating part of original float number x. Count is calculated as difference between length of original number x and number n in their string representation.

看了几个之后,我现在用的是……

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