split not working

后端 未结 3 995
余生分开走
余生分开走 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: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

提交回复
热议问题