programing

JavaScript를 사용하여 숫자의 소수점 부분 가져오기

sourcejob 2022. 9. 22. 00:17
반응형

JavaScript를 사용하여 숫자의 소수점 부분 가져오기

나는 다음과 같은 플로트 번호를 가지고 있다.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

내가 뭘 놓쳤지?

1 아니라, 이에요.2.

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.29999999999999998은 어떻게 대답할 수 있을까요?내가 질문자라면 3점 만점에 대한 답변을 원할 것이다.여기 있는 것은 false precision입니다.제가 floor, % 등을 실험한 결과, Javascript는 이러한 조작에 대해 false precision을 좋아하는 것으로 나타났습니다.그래서 현악기로의 변환에 대한 답은 올바른 방향으로 가고 있다고 생각합니다.

나는 이렇게 할 것이다:

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

구체적으로는 100233.1을 사용하고 있었는데, 「.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

fractioanal lenght가 1개 있는 수치에만 해당됩니다.

하시면 됩니다.parseInt()

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

또는 다음과 같은 regex를 사용할 수 있습니다.

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

예쁘지는 않지만 정확해요.

정밀도가 중요하여 일관된 결과가 필요한 경우 선행하는 "0"을 포함하여 임의의 숫자의 소수 부분을 문자열로 반환하는 몇 가지 명제가 있습니다.하시면 그냥 .var f = parseFloat( result )★★★★★★★★★★★★★★★★★★.

소수점 부분이 0이면 "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.index Of

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번 제안이 가장 빠르다는 것을 알 수 있습니다.

숫자를 문자열로 변환한 후 분할하는 것이 좋습니다.

// 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 a = 10.2
var c = a.toString().split(".")
console.log(c[1] == 2) //True
console.log(c[1] === 2)  //False

그러나 @Brian M이 제안한 솔루션보다 시간이 더 걸립니다.헌트

(2.3 % 1).toFixed(4)

사용하고 있는 것:

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.12344444

결과: 123444444

스트링으로 변환하여replace정수 부분을 0으로 바꾼 다음 결과를 수치로 다시 변환하는 방법:

var number = 123.123812,
    decimals = +number.toString().replace(/^[^\.]+/,'0');
n = Math.floor(x);
remainder = x % 1;

산술 함수는 더 빠르지만 항상 기본 기대값이 아닌 값을 반환합니다.제가 찾은 가장 쉬운 방법은

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

수학적 부정확성을 피하는 가장 좋은 방법은 문자열로 변환하는 것이지만 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))

간단하게 사용할 수 있습니다.parseInt()예를 들어 다음과 같습니다.

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

문제의 모든 숫자가 소수점 하나밖에 없다는 것을 알고 소수점 부분을 정수로 얻으려고 해서 다음과 같은 방법을 사용했습니다.

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

이 방법은 정수에서도 잘 작동하며, 이 경우 0을 반환합니다.

이 답변이 마음에 듭니다.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를 어디에나 적용하시기 바랍니다.감사합니다!

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

이것들 몇 개를 보고 지금 사용하고 있는 것은...

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. 소수점 이하가 0인 숫자가 있습니다만, JavaScript를 사용하면 플로팅 파트 디지트를 추가할 수 있습니다.
  6. 때문에, 「자릿수」, 「자릿수」를 하는 것으로, 합니다.toFixed() number의 부분에 경우x 숫자의 길이 x 넘버 및n이치노

이 함수는 플로트 번호를 정수로 분할하여 배열로 반환합니다.

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'CHANGE: 'CHANGE: 'CHANGE: 'CHANGE:

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 ]

번호를 잘라낼 수도 있습니다.

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

다음 함수는 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)

예를 들어 두 개의 숫자를 추가하는 경우

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

언급URL : https://stackoverflow.com/questions/4512306/get-decimal-portion-of-a-number-with-javascript

반응형