简体   繁体   中英

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%

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);
}

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%

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM