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

我错过了什么?


当前回答

你可以转换成字符串,对吧?

n = (n + "").split(".");

其他回答

为什么0.2999999999999998是一个可以接受的答案?如果我是提问者,我希望答案是。3。我们在这里得到的是错误的精度,我对floor、%等的实验表明,Javascript对这些操作喜欢错误的精度。所以我认为使用字符串转换的答案是正确的。

我会这样做:

var decPart = (n+"").split(".")[1];

具体来说,我使用100233.1,我想要答案“.1”。

使用1,而不是2。

js> 2.3 % 1
0.2999999999999998

我喜欢这个答案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。谢谢!

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

函数拆分数(数) { 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 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)