在Javascript中删除十进制后的数字

时间:2015-02-27 15:05:50

标签: javascript decimal calculator

我正在制作一个从GPS度数,十进制分钟到度,分,秒的转换器,因为我在互联网上找不到一个。

请告诉我如何摆脱计算总字段中小数点后的数字?

<HEAD>

<TITLE>Javascript Calculator</TITLE>

<SCRIPT language="javascript" type="text/javascript">
function multiply()
{
a=Number(document.calculator.number1.value);
b=.060;
c=a*b;
document.calculator.total.value=c;
}
</SCRIPT>

</HEAD>

<BODY>
<FORM name="calculator">

Decimal: <INPUT type="text" name="number1"> <br>
<INPUT type="button" value="Calculate" onclick="javascript:multiply();"><br>
Seconds: <INPUT type="text" name="total">
</FORM>
</BODY>

3 个答案:

答案 0 :(得分:1)

以下内容应该适合您。改变了原始的一些内容,但这只是因为id比name更好,因为name带来了一个nodelist。

<HEAD>

<TITLE>Javascript Calculator</TITLE>

</HEAD>

<BODY>
<FORM name="calculator">Decimal:
    <INPUT type="text" id="number1">
    <br>
    <INPUT type="button" value="Calculate" id="calculate">
    <br>Seconds:
    <INPUT type="text" id="total">
</FORM>

<script>
// put your script tags at the bottom of the page
// first get the calculate button by its Id.
var calculate = document.getElementById('calculate');
// then add an event listener to it that calls multiply function when clicked
calculate.addEventListener('click', multiply, false);

// this multiply function is called when the button is clicked
function multiply() {
    // get the inputs value then the total input fields by id
    var a = document.getElementById('number1').value;
    var total = document.getElementById('total');

    var b = 0.060;
    // Math.floor is used to round down since you just want to remove the numbers after decimal.
    var c = Math.floor(a * b);

    // set the value of total
    total.value = c;
}
</script>
</BODY>

答案 1 :(得分:0)

Math.round(x) //x being your number you wish to 'round

JSFiddle:http://jsfiddle.net/j37m78a4/2/

我已经注释掉了提供小数点值答案的代码。取消注释并注释掉它下面的行以查看原始答案是什么。 :)

如果您不知道将代码放在何处,我建议您阅读Javascript书籍或阅读在线教程以首先了解基础知识。通过直接跳到项目开始很好,但在执行此操作之前需要了解基础知识。 :)

答案 2 :(得分:0)

最快的是使用右移运算符的按位移位。 c = 5.674447&gt;&gt; 0