split not working

后端 未结 3 899
余生分开走
余生分开走 2020-12-07 06:29

How do i split decimal numbers? The variable bidnumber is 10.70.

var bidnumber = $(this).parent(\'div\').siblings(\'.advert-details         


        
相关标签:
3条回答
  • 2020-12-07 06:42
    • The attribute value is already a string, so you don't have to convert it to a string.
    • The split method doesn't put the array back in the variable.
    • The substr method doesn't put the new string back in the variable.

    So:

    bidnumber = bidnumber.split('.');
    var first = bidnumber[0];
    var second = bidnumber[1];
    second = second.substr(0, 1);
    var finalnumber = first + '.' + second;
    

    Or just:

    bidnumber = bidnumber.split('.');
    bidnumber[1] = bidnumber[1].substr(0, 1);
    var finalnumber = bidnumber.join('.');
    

    Consider also to parse the string to a number and round it:

    var finalnumber = Math.round(parseFloat(bidnumber) * 10) / 10;
    
    0 讨论(0)
  • 2020-12-07 06:43

    You should not use split to break apart the integer and fractional parts of a number.

    For example, 10.70 when split (and converting the 70 to cents) would give a different answer to 10.7 even though they're the same number.

    var bidnumber = 10.70;     // ignoring your DOM query for now
    
    var whole = ~~bidnumber;   // quick and nasty 'truncate' operator
    var cents = 100 * Math.abs(bidnumber - whole);
    

    The final line ensures that the number of cents is positive even if the original number was negative.

    The ~~ operator is actually two instances of the ~ operator, which is a bitwise "not" operator that truncates any number to a 32 bit signed value, throwing away any fractional part. Flipping twice gives the original number, but without the fraction.

    That's the easiest way to get a "round towards zero" result, as Math.floor() would actually give -11 for an input of -10.70

    0 讨论(0)
  • 2020-12-07 06:53

    You forgot to return the array back from split function:

    bidnumber = bidnumber.toString().split('.');
    
    0 讨论(0)
提交回复
热议问题