在javascript中将单个数字更改为两位数

时间:2012-08-29 20:41:57

标签: javascript

如何在输出中为百分比添加零? 这是代码:

    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;

.40保证金的输出总是4%。我需要40%

2 个答案:

答案 0 :(得分:1)

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

修改

你说“但我得到两个百分号” ......那么这应该是你的formatPercentage功能:

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

答案 1 :(得分:0)

在你的帖子中你可能想说“.40保证金的输出总是.4%。我需要它是40%”,对吧? 将您的保证金乘以100,您将获得40%而不是.4%