Javascript javascript中的整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5815411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
whole number in javascript?
提问by ktm
I get 28.6813276578 when i multiply 2 numbers a and b, how can i make it whole number with less digits
当我将 2 个数字 a 和 b 相乘时,我得到 28.6813276578,我怎样才能用更少的数字使它成为整数
and also, when i multiply again i get results after first reult like 28.681321405.4428.68 how to get only one result ?
而且,当我再次相乘时,我在第一次结果后得到结果,如 28.681321405.4428.68 如何只得到一个结果?
<script>
$(document).ready(function(){
$("#total").hide();
$("#form1").submit(function(){
var a = parseFloat($("#user_price").val());
var b = parseFloat($("#selling").val());
var total = a*b;
$("#total").append(total)
.show('slow')
.css({"background":"yellow","font-size":50})
;
return false;
});
});
</script>
回答by Jason
You can do several things:
你可以做几件事:
total = total.toFixed([number of decimals]);
total = Math.round(total);
total = parseInt(total);
toFixed()
will round your number to the number of decimals indicated.Math.round()
will round numbers to the nearest integer.parseInt()
will take a string and attempt to parse an integer from it without rounding.parseInt()
is a little trickier though, in that it will parse the first characters in a string that are numbers until they are not, meaningparseInt('123g32ksj')
will return123
, whereasparseInt('sdjgg123')
will returnNaN
.- For the sake of completeness,
parseInt()
accepts a second parameter which can be used to express the base you're trying to extract with, meaning that, for instance,parseInt('A', 16) === 10
if you were trying to parse a hexidecimal.
- For the sake of completeness,
toFixed()
会将您的数字四舍五入到指定的小数位数。Math.round()
将数字四舍五入到最接近的整数。parseInt()
将采用一个字符串并尝试从中解析一个整数而不舍入。parseInt()
不过有点棘手,因为它将解析字符串中的第一个字符,直到它们不是数字为止,这意味着parseInt('123g32ksj')
将返回123
,而parseInt('sdjgg123')
将返回NaN
。- 为了完整起见,
parseInt()
接受第二个参数,该参数可用于表示您尝试提取的基数,这意味着,例如,parseInt('A', 16) === 10
如果您试图解析一个十六进制。
- 为了完整起见,
回答by DuckMaestro
回答by SHug
In addition to the other answers about rounding, you are appending the answer to "total" by using
除了有关四舍五入的其他答案之外,您还使用以下方法将答案附加到“总计”
$("#total").append(total)
You need to replace the previous text rather than appending by using
您需要替换以前的文本而不是使用附加
$("#total").html(total)