How do i split decimal numbers? The variable bidnumber
is 10.70
.
var bidnumber = $(this).parent(\'div\').siblings(\'.advert-details
split
method doesn't put the array back in the variable.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;
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
You forgot to return the array back from split
function:
bidnumber = bidnumber.toString().split('.');