Tommy
Tommy

Reputation: 113

Changing single digit number to double digit in javascript

How can I add a zero to a to the output for a percentage? Here is the code:

    var margin = 0;             
    if(total_quantity>1000){margin = .32;}
    else if(total_quantity>575){margin = .35;}
    else if(total_quantity>143){margin = .36;}
    else if(total_quantity>71){margin = .38;}
    else if(total_quantity>36){margin = .40;}
    else{margin = .55;} 
    document.getElementById('margin').value=margin;

The output of the .40 margin is always 4%. I need it to be 40%

Upvotes: 2

Views: 231

Answers (2)

artlung
artlung

Reputation: 33813

var margin = 0;
if (total_quantity > 1000) {
    margin = .32;
} else if (total_quantity > 575) {
    margin = .35;
} else if (total_quantity > 143) {
    margin = .36;
} else if (total_quantity > 71) {
    margin = .38;
} else if (total_quantity > 36) {
    margin = .40;
} else {
    margin = .55;
}
function formatPercentage (decimalNumber) {
    return parseInt(decimalNumber * 100, 10); + "%";
}

document.getElementById('margin').value = formatPercentage(margin);

EDIT

You said "but I'm getting two percent signs"... then this should be your formatPercentage function:

function formatPercentage (decimalNumber) {
    return parseInt(decimalNumber * 100, 10);
}

Upvotes: 1

Grzegorz
Grzegorz

Reputation: 3335

In your post you probably wanted to say "The output of the .40 margin is always .4%. I need it to be 40%", right? Multiply your margin by 100 and you will get 40% instead of .4%

Upvotes: 0

Related Questions