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

发布于 2024-10-08 19:50:44 字数 432 浏览 5 评论 0原文

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

我在这里缺少什么?

I have float numbers like 3.2 and 1.6.

I need to separate the number into the integer and decimal part. For example, a value of 3.2 would be split into two numbers, i.e. 3 and 0.2

Getting the integer portion is easy:

n = Math.floor(n);

But I am having trouble getting the decimal portion.
I have tried this:

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

But it does not always work correctly.

The previous code has the following output:

n = 3.1 // gives remainder = 1.1

What I am missing here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

萌无敌 2024-10-15 19:50:44

使用1,而不是2

js> 2.3 % 1
0.2999999999999998

Use 1, not 2.

js> 2.3 % 1
0.2999999999999998
海之角 2024-10-15 19:50:44
var decimal = n - Math.floor(n)

虽然这不适用于负数,所以我们可能不得不这样做

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

Although this won't work for minus numbers so we might have to do

n = Math.abs(n); // Change to positive
var decimal = n - Math.floor(n)
定格我的天空 2024-10-15 19:50:44

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

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

You could convert to string, right?

n = (n + "").split(".");
白衬杉格子梦 2024-10-15 19:50:44

0.2999999999999998 如何是可接受的答案?如果我是提问者,我会想要 0.3 的答案。我们这里有的是假精度,我对下限、% 等的实验表明 Javascript 喜欢这些操作的假精度。所以我认为使用转换为字符串的答案是正确的。

我会这样做:

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

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

How is 0.2999999999999998 an acceptable answer? If I were the asker I would want an answer of .3. What we have here is false precision, and my experiments with floor, %, etc indicate that Javascript is fond of false precision for these operations. So I think the answers that are using conversion to string are on the right track.

I would do this:

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

Specifically, I was using 100233.1 and I wanted the answer ".1".

辞取 2024-10-15 19:50:44

这是我的做法,我认为这是最直接的方法:

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

Here's how I do it, which I think is the most straightforward way to do it:

var x = 3.2;
var int_part = Math.trunc(x); // returns 3
var float_part = Number((x-int_part).toFixed(2)); // return 0.2
梦醒时光 2024-10-15 19:50:44

一个简单的方法是:

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

A simple way of doing it is:

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

Unfortunately, that doesn't return the exact value. However, that is easily fixed:

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

You can use this if you don't know the number of decimal places:

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

过潦 2024-10-15 19:50:44

不依赖任何标准 JS 函数:

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

请注意,它仅对于具有一位小数点的数字是正确的。

Without relying on any standard JS functions:

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

Note that it is correct only for numbers with one decimal point.

栖迟 2024-10-15 19:50:44

您可以使用 parseInt() 函数来获取整数部分,而不是使用它来提取小数部分

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

You can use parseInt() function to get the integer part than use that to extract the decimal part

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

Or you could use regex like:

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]}`)
       }
   }
}
勿挽旧人 2024-10-15 19:50:44

如果精度很重要并且您需要一致的结果,这里有一些命题,它们会将任何数字的小数部分作为字符串返回,包括前导“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是最快。

If precision matters and you require consistent results, here are a few propositions that will return the decimal part of any number as a string, including the leading "0.". If you need it as a float, just add var f = parseFloat( result ) in the end.

If the decimal part equals zero, "0.0" will be returned. Null, NaN and undefined numbers are not tested.

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

Here is a jsPerf link: https://jsperf.com/decpart-of-number/

We can see that proposition #2 is the fastest.

白云悠悠 2024-10-15 19:50:44

只需使用模 1 即可。

remainder = x % 1;

Just use modulo 1.

remainder = x % 1;
樱花细雨 2024-10-15 19:50:44

一个好的选择是将数字转换为字符串,然后将其拆分。

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

A good option is to transform the number into a string and then split it.

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

In one line of code

let [firstNumber, secondNumber] = [+number.toString().split('.')[0], +number.toString().split('.')[1]];
怪我入戏太深 2024-10-15 19:50:44

无论小数点分隔符的区域设置如何,以下操作都有效...条件是仅使用一个字符作为分隔符。

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

它不漂亮,但很准确。

The following works regardless of the regional settings for decimal separator... on the condition only one character is used for a separator.

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

It ain't pretty, but it's accurate.

×纯※雪 2024-10-15 19:50:44

取决于您随后给出的用法,但这个简单的解决方案也可以帮助您。

我并不是说它是一个好的解决方案,但对于某些具体情况有效

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

,但它需要比 @Brian M. Hunt 提出的解决方案更长的时间

(2.3 % 1).toFixed(4)

Depending the usage you will give afterwards, but this simple solution could also help you.

Im not saying its a good solution, but for some concrete cases works

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

But it will take longer than the proposed solution by @Brian M. Hunt

(2.3 % 1).toFixed(4)
酒绊 2024-10-15 19:50:44

您可以简单地使用 parseInt() 函数来帮助,例如:

let decimal = 3.2;
let remainder = decimal - parseInt(decimal);
document.write(remainder);

You can simply use parseInt() function to help, example:

let decimal = 3.2;
let remainder = decimal - parseInt(decimal);
document.write(remainder);

夏末的微笑 2024-10-15 19:50:44

解决方案

最简单的方法是使用 mod (%) 运算符:

var decimal = n % 1;

说明

mod 运算符给出算术除法的余数。

示例14 % 4 是 2,因为 14 / 4 是 3,其余数是 2。

那么,由于 n % 1< /code> 始终在 0 和 1 之间或 [0, 1) 它对应于 n 的小数部分。

Solution

The simplest way is to use the mod (%) operator:

var decimal = n % 1;

Explanation

The mod operator gives the remainder of the arithmetical division.

Example: 14 % 4 is 2 because 14 / 4 is 3 and its remainder is 2.

Then, since n % 1 is always between 0 and 1 or [0, 1) it corresponds to the decimal part of n.

淡莣 2024-10-15 19:50:44

我正在使用:

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

输入:-556.123444444

结果:123444444

I am using:

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

Input: -556.123444444

Result: 123444444

怼怹恏 2024-10-15 19:50:44

您可以将其转换为字符串并使用 replace 方法将整数部分替换为零,然后将结果转换回数字:

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

You could convert it to a string and use the replace method to replace the integer part with zero, then convert the result back to a number :

var number = 123.123812,
    decimals = +number.toString().replace(/^[^\.]+/,'0');
想挽留 2024-10-15 19:50:44

数学函数速度更快,但始终返回的不是本机预期值。
我发现的最简单的方法是

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

Math functions are faster, but always returns not native expected values.
Easiest way that i found is

(3.2+'').replace(/^[-\d]+\./, '')
素染倾城色 2024-10-15 19:50:44

避免数学不精确的最佳方法是转换为字符串,但使用 toLocaleString 确保它采用您期望的“点”格式:

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

The best way to avoid mathematical imprecision is to convert to a string, but ensure that it is in the "dot" format you expect by using toLocaleString:

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

拥抱我好吗 2024-10-15 19:50:44

我遇到过一种情况,我知道所有相关数字都只有一位小数,并且希望将小数部分作为整数获取,因此我最终使用了这种方法:

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

这也适用于整数,在这些情况下返回 0。

I had a case where I knew all the numbers in question would have only one decimal and wanted to get the decimal portion as an integer so I ended up using this kind of approach:

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

This works nicely also with integers, returning 0 in those cases.

小帐篷 2024-10-15 19:50:44

虽然我很晚才回答这个问题,但请看一下代码。

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)

Although I am very late to answer this, please have a look at the code.

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)
ゃ懵逼小萝莉 2024-10-15 19:50:44

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

积极如果您是加密货币交易平台开发人员或银行系统开发人员或任何 JS 开发人员;)请在任何地方应用 fpFix。谢谢!

I like this answer https://stackoverflow.com/a/4512317/1818723 just need to apply float point fix

function fpFix(n) {
  return Math.round(n * 100000000) / 100000000;
}

let decimalPart = 2.3 % 1; //0.2999999999999998
let correct = fpFix(decimalPart); //0.3

Complete function handling negative and positive

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. If you are cryptocurrency trading platform developer or banking system developer or any JS developer ;) please apply fpFix everywhere. Thanks!

孤君无依 2024-10-15 19:50:44

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

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

After looking at several of these, I am now using...

var rtnValue = Number(7.23);
var tempDec = ((rtnValue / 1) - Math.floor(rtnValue)).toFixed(2);
感情废物 2024-10-15 19:50:44

浮点小数符号和数字格式可能与国家相关(.,),因此保留浮点部分的独立解决方案是:

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. 因此,通过调用 < 来限制额外的数字code>toFixed() 包含原始浮点数 x 的浮动部分的位数。计数是根据字符串表示形式中原始数字 x 和数字 n 的长度之间的差异来计算的。

Floating-point decimal sign and number format can be dependent from country (.,), so independent solution, which preserved floating point part, is:

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

– it is internationalized solution, instead of location-dependent:

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

Solution desription step by step:

  1. parseFloat() for guaranteeing input cocrrection
  2. Math.abs() for avoiding problems with negative numbers
  3. n = parseInt(x) for getting decimal part
  4. x - n for substracting decimal part
  5. We have now number with zero decimal part, but JavaScript could give us additional floating part digits, which we do not want
  6. 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.
幽梦紫曦~ 2024-10-15 19:50:44

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

2021 Update

Optimized version that tackles precision (or not).

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

旧瑾黎汐 2024-10-15 19:50:44

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

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 ]

This function splits float number into integers and returns it in array:

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 ]

You can extend it to only return existing numbers and null if no number exists:

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 ]

往日 2024-10-15 19:50:44

您还可以截断数字

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

You can also truncate the number

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

独享拥抱 2024-10-15 19:50:44

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

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)

The following function will return an array which will have 2 elements. The first element will be the integer part and the second element will be the decimal part.

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)

成熟稳重的好男人 2024-10-15 19:50:44

例如两个数字相加

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);
}

For example for add two numbers

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);
}
怎会甘心 2024-10-15 19:50:44

还有另一种方式:

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

fract(2.3) // <-- 0.2999999999999998

Yet another way:

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

fract(2.3) // <-- 0.2999999999999998
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文