我在使用轉換權重的我的網站上使用腳本。 Math.round函數正常工作,但我需要格式化「結果」,如下所示:ex。 1.000,000。今天這個數字顯示爲1000.000。有誰知道該怎麼辦?我嘗試了一些number_format的東西,但不能。請按照下面的代碼:math.round數字格式
<script>
function convert() {
var amount = document.getElementById("amount").value,
measurement_from = document.getElementById("measurement_from"),
measurement_from_name = measurement_from.options[measurement_from.selectedIndex].text,
measurement_from_type = measurement_from.options[measurement_from.selectedIndex].getAttribute('data-type'),
measurement_from_value = measurement_from.options[measurement_from.selectedIndex].getAttribute('data-value'),
measurement_to = document.getElementById("measurement_to"),
measurement_to_name = measurement_to.options[measurement_to.selectedIndex].text,
measurement_to_type = measurement_to.options[measurement_to.selectedIndex].getAttribute('data-type'),
measurement_to_value = measurement_to.options[measurement_to.selectedIndex].getAttribute('data-value'),
ingredient = document.getElementById("ingredient"),
ingredient_name = ingredient.options[ingredient.selectedIndex].text,
ingredient_density = ingredient.options[ingredient.selectedIndex].getAttribute('data-density'),
total_volume,
result,
result_text,
result_div = document.getElementById("result");
if (measurement_from_type == 'weight')
total_volume = amount * measurement_from_value/ingredient_density;
else
total_volume = amount * measurement_from_value;
if (measurement_to_type == 'weight')
result = total_volume/measurement_to_value * ingredient_density;
else
result = total_volume/measurement_to_value;
result = Math.round(result * 1000)/1000;
result_text = result + ' ' + measurement_to_name ;
while(result_div.firstChild) {
result_div.removeChild(result_div.firstChild);
}
result_div.appendChild(document.createTextNode(result_text));
}
</script>
謝謝!
你可能會考慮這個標記'javascript'而不是'php',因爲這是你發佈的代碼是 –
對不起,我的錯。 – Rodolfo
結果是完全沒問題,Math.round(1234.5678124 * 1000)/ 1000結果爲1234.5678 - 所以你想要的是舍入,然後以可打印的格式格式化數字的字符串格式 – nemoinho