Programing

숫자에서 중요하지 않은 후행 0을 제거 하시겠습니까?

lottogame 2020. 6. 28. 18:29
반응형

숫자에서 중요하지 않은 후행 0을 제거 하시겠습니까?


숫자에서 후미의 0을 제거하는 표준 API 호출을 놓쳤습니까?

전의.

var x = 1.234000 // to become 1.234;
var y = 1.234001; // stays 1.234001

Number.toFixed () 및 Number.toPrecision ()은 내가 찾고있는 것이 아닙니다.


문자열로 변환하면 문자열이 아닌 숫자로 작성된 이후 변수에 저장되지 않는 후행 0이 표시되지 않습니다.

var n = 1.245000
var noZeroes = n.toString() // "1.245" 

필자는 .toFixed()필요한 곳 에서 사용 하고 싶었던 비슷한 인스턴스를 가지고 있었지만 그렇지 않을 때 패딩을 원하지 않았습니다. 그래서 toFixed와 함께 parseFloat를 사용했습니다.

패딩없이 고정

parseFloat(n.toFixed(4));

거의 같은 일을하는 다른 옵션
이 답변은 결정에 도움이 될 수 있습니다

Number(n.toFixed(4));

toFixed숫자를 특정 길이로 반올림 / 채울뿐만 아니라 문자열로 변환합니다. 다시 숫자 형식으로 변환하면 숫자를 산술적으로 사용하는 것이 더 안전 할뿐만 아니라 후행 0을 자동으로 삭제합니다. 예를 들면 다음과 같습니다.

var n = "1.234000";
    n = parseFloat(n);
 // n is 1.234 and in number form

후행 0으로 숫자를 정의하더라도 삭제됩니다.

var n = 1.23000;
 // n == 1.23;

나는 먼저 matti-lyra와 gary의 답변을 조합하여 사용했습니다.

r=(+n).toFixed(4).replace(/\.0+$/,'')

결과 :

  • 1234870.98762341 : "1234870.9876"
  • 1230009100 : "1230009100"
  • 0.0012234 : "0.0012"
  • 0.1200234 : "0.12"
  • 0.000001231 : "0"
  • 0.10001 : "0.1000"
  • "asdf": "NaN"(런타임 오류가 없음)

다소 문제가되는 경우는 0.10001입니다. 이 긴 버전을 사용하게되었습니다.

    r = (+n).toFixed(4);
    if (r.match(/\./)) {
      r = r.replace(/\.?0+$/, '');
    }
  • 1234870.98762341 : "1234870.9876"
  • 1230009100 : "1230009100"
  • 0.0012234 : "0.0012"
  • 0.1200234 : "0.12"
  • 0.000001231 : "0"
  • 0.10001 : "0.1"
  • "asdf": "NaN"(런타임 오류가 없음)

업데이트 : 이것은 Gary의 최신 버전입니다 (의견 참조).

r=(+n).toFixed(4).replace(/([0-9]+(\.[0-9]+[1-9])?)(\.?0+$)/,'$1')

위와 동일한 결과를 제공합니다.


toFixed방법은 필요한 경우 적절한 반올림을 수행합니다. 또한 항상 0이 아닌 후행 0을 추가합니다.

(4.55555).toFixed(2);
//-> "4.56"

(4).toFixed(2);
//-> "4.00"

반환 값을 숫자로 캐스팅하면 후행 0이 삭제됩니다. 이것은 자신의 반올림 또는 절단 수학을 수행하는 것보다 간단한 접근 방법입니다.

+(4.55555).toFixed(2);
//-> 4.56

+(4).toFixed(2);
//-> 4

Django가 Decimal 유형 값을 텍스트 필드에 표시 할 때이 문제도 해결해야했습니다. 예를 들어 '1'이 값일 때 '1.00000000'으로 표시됩니다. '1.23'이 값이면 '1.23000000'을 표시합니다 ( 'decimal_places'설정이 8 인 경우)

parseFloat사용 하는 것은 옵션이 아닙니다. 정확히 동일한 값을 반환하지 않을 수도 있기 때문입니다. toFixed 는 아무것도 반올림하지 않기 때문에 옵션이 아니므로 함수를 만들었습니다.

function removeTrailingZeros(value) {
    value = value.toString();

    # if not containing a dot, we do not need to do anything
    if (value.indexOf('.') === -1) {
        return value;
    }

    # as long as the last character is a 0 or a dot, remove it
    while((value.slice(-1) === '0' || value.slice(-1) === '.') && value.indexOf('.') !== -1) {
        value = value.substr(0, value.length - 1);
    }
    return value;
}

순수한 정규식 답변

n.replace(/(\.[0-9]*[1-9])0+$|\.0*$/,'$1');

I wonder why no one gave one!


I had the basically the same requirement, and found that there is no built-in mechanism for this functionality.

In addition to trimming the trailing zeros, I also had the need to round off and format the output for the user's current locale (i.e. 123,456.789).

All of my work on this has been included as prettyFloat.js (MIT Licensed) on GitHub: https://github.com/dperish/prettyFloat.js


Usage Examples:

prettyFloat(1.111001, 3) // "1.111"
prettyFloat(1.111001, 4) // "1.111"
prettyFloat(1.1111001, 5) // "1.1111"
prettyFloat(1234.5678, 2) // "1234.57"
prettyFloat(1234.5678, 2, true) // "1,234.57" (en-us)


Updated - August, 2018


All modern browsers now support the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting.

let formatters = {
    default: new Intl.NumberFormat(),
    currency: new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 0, maximumFractionDigits: 0 }),
    whole: new Intl.NumberFormat('en-US', { style: 'decimal', minimumFractionDigits: 0, maximumFractionDigits: 0 }),
    oneDecimal: new Intl.NumberFormat('en-US', { style: 'decimal', minimumFractionDigits: 1, maximumFractionDigits: 1 }),
    twoDecimal: new Intl.NumberFormat('en-US', { style: 'decimal', minimumFractionDigits: 2, maximumFractionDigits: 2 })
};

formatters.twoDecimal.format(1234.5678);  // result: "1,234.57"
formatters.currency.format(28761232.291); // result: "$28,761,232"

For older browsers, you can use this polyfill: https://cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.en


How about just multiplying by one like this?

var x = 1.234000*1; // becomes 1.234

var y = 1.234001*1; // stays as 1.234001

You can try this one to minify floating numbers

var n = 0.0000;
n = parseFloat(n.toString()); 

//output n = 0; 
// n = 3.14000; --> n = 3.14;

None of these solutions worked for me for very small numbers. http://numeraljs.com/ solved this for me.

parseFloat(0.00000001.toFixed(8));
// 1e-8

numeral(0.00000001).format('0[.][00000000]');
// "0.00000001"

If you cannot use Floats for any reason (like money-floats involved) and are already starting from a string representing a correct number, you could find this solution handy. It converts a string representing a number to a string representing number w/out trailing zeroes.

function removeTrailingZeroes( strAmount ) {
    // remove all trailing zeroes in the decimal part
    var strDecSepCd = '.'; // decimal separator
    var iDSPosition = strAmount.indexOf( strDecSepCd ); // decimal separator positions
    if ( iDSPosition !== -1 ) {
        var strDecPart = strAmount.substr( iDSPosition ); // including the decimal separator

        var i = strDecPart.length - 1;
        for ( ; i >= 0 ; i-- ) {
            if ( strDecPart.charAt(i) !== '0') {
                break;
            }
        }

        if ( i=== 0 ) {
            return strAmount.substring(0, iDSPosition);
        } else {
            // return INTPART and DS + DECPART including the rightmost significant number
            return strAmount.substring(0, iDSPosition) + strDecPart.substring(0,i + 1);
        }
    }

    return strAmount;
}

After reading all of the answers - and comments - I ended up with this:

function isFloat(n) {
    let number = (Number(n) === n && n % 1 !== 0) ? eval(parseFloat(n)) : n;
    return number;
}

I know using eval can be harmful somehow but this helped me a lot.

So:

isFloat(1.234000);     // = 1.234;
isFloat(1.234001);     // = 1.234001
isFloat(1.2340010000); // = 1.234001

If you want to limit the decimal places, use toFixed() as others pointed out.

let number = (Number(n) === n && n % 1 !== 0) ? eval(parseFloat(n).toFixed(3)) : n;

That's it.


I needed to remove any trailing zeros but keep at least 2 decimals, including any zeros.
The numbers I'm working with are 6 decimal number strings, generated by .toFixed(6).

Expected Result:

var numstra = 12345.000010 // should return 12345.00001
var numstrb = 12345.100000 // should return 12345.10
var numstrc = 12345.000000 // should return 12345.00
var numstrd = 12345.123000 // should return 12345.123

Solution:

var numstr = 12345.100000

while (numstr[numstr.length-1] === "0") {           
    numstr = numstr.slice(0, -1)
    if (numstr[numstr.length-1] !== "0") {break;}
    if (numstr[numstr.length-3] === ".") {break;}
}

console.log(numstr) // 12345.10

Logic:

Run loop function if string last character is a zero.
Remove the last character and update the string variable.
If updated string last character is not a zero, end loop.
If updated string third to last character is a floating point, end loop.


Here's a possible solution:

var x = 1.234000 // to become 1.234;
var y = 1.234001; // stays 1.234001

eval(x) --> 1.234
eval(y) --> 1.234001

Just a simple math alternative to using toFixed

function truncateNumber( num, precision ){
    let c = Math.pow(10,precision);
    return Math.trunc( num*c )/c;
}
    
console.log( truncateNumber(1234.5678, 4) );
console.log( truncateNumber(1234.56, 4) );

참고URL : https://stackoverflow.com/questions/3612744/remove-insignificant-trailing-zeros-from-a-number

반응형