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

2020/10/09 02:41 · javascript ·  · 0评论

``````n = Math.floor(n);
``````

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

``````n = 3.1 => remainer = 1.1
``````

``````js> 2.3 % 1
0.2999999999999998
``````
``````var decimal = n - Math.floor(n)
``````

``````n = Math.abs(n); // Change to positive
var decimal = n - Math.floor(n)
``````

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

0.2999999999999998如何接受？如果我是提问者，我希望得到.3。的答案。这里的错误精度是错误的，我对floor，％等的实验表明Javascript喜欢这些操作的错误精度。因此，我认为使用转换为字符串的答案是正确的。

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

``````var x = 3.2;
int_part = Math.trunc(x); // returns 3
float_part = Number((x-int_part).toFixed(2)); // return 0.2
``````

``````var x = 3.2;
var decimals = x - Math.floor(x);
console.log(decimals); //Returns 0.20000000000000018``````

``````var x = 3.2;
var decimals = x - Math.floor(x);
console.log(decimals.toFixed(1)); //Returns 0.2``````

``````var x = 3.2;
var decimals = x - Math.floor(x);

var decimalPlaces = x.toString().split('.')[1].length;
decimals = decimals.toFixed(decimalPlaces);

console.log(decimals); //Returns 0.2``````

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

``````var myNumber = 3.2;
var integerPart = parseInt(myNumber);
var decimalPart = myNumber - integerPart;
``````

``````splitFloat = function(n){
const regex = /(\d*)[.,]{1}(\d*)/;
var m;

if ((m = regex.exec(n.toString())) !== null) {
return {
integer:parseInt(m[1]),
decimal:parseFloat(`0.\${m[2]}`)
}
}
}
``````

``````var n = 2015.15;
var integer = Math.floor(n).toString();
var strungNumber = n.toString();
if (integer.length === strungNumber.length)
return "0";
return strungNumber.substring(integer.length + 1);
``````

# 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");
``````

``````var number = 123.123812,
decimals = +number.toString().replace(/^[^\.]+/,'0');
``````

``````var a = 10.2
var c = a.toString().split(".")
console.log(c[1] == 2) //True
console.log(c[1] === 2)  //False
``````

``````(2.3 % 1).toFixed(4)
``````

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

``````var number = 3.1,
decimalAsInt = Math.round((number - parseInt(number)) * 10); // returns 1
``````

``````var n = -556.123444444;
var str = n.toString();
var decimalOnly = 0;

if( str.indexOf('.') != -1 ){ //check if has decimal
var decimalOnly = parseFloat(Math.abs(n).toString().split('.')[1]);
}
``````

``````n = Math.floor(x);
remainder = x % 1;
``````

``````(3.2+'').replace(/^[-\d]+\./, '')
``````

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

``````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)
``````

``````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]));
``````

1. `parseFloat()` 用于保证输入的正确性
2. `Math.abs()` 用于避免负数问题
3. `n = parseInt(x)` 获取小数部分
4. `x - n` 用于减去小数部分
5. 现在，我们的数字的小数部分为零，但是JavaScript可以为我们提供额外的浮动部分数字，这是我们不想要的
6. 因此，通过调用`toFixed()`原始浮点数的浮点部分中的位数来限制其他位数`x`计算为原始数字的长度`x``n`其字符串表示形式的数字之间的差

``````function getDecimals(n) {
// Note that maximumSignificantDigits defaults to 3 so your decimals will be rounded if not changed.
const parts = n.toLocaleString('en-US', { maximumSignificantDigits: 18 }).split('.')
return parts.length > 1 ? Number('0.' + parts[1]) : 0
}

console.log(getDecimals(10.58))``````
``````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
``````