javascript:如何将数字四舍五入到最接近的 10 美分?

标签 javascript

我想将“189.46”四舍五入为 189.5

这是一个示例,如果我们以字符串形式开始数字。谁能告诉我为什么我的方法不起作用以及正确的方法是什么?

Math.round(parseFloat('189.46')).toFixed(1);

最佳答案

将数字乘以 10 并四舍五入(使用提供的 189.46 - 这将得到 1895),然后除以 10 以返回十进制数(在本例中为 189.5)。

假设您要求它从输入中获取一个值 - 而不是硬编码的字符串/数字 - 我提供了一个用于输入值的输入和一个在点击事件时触发舍入功能的按钮。

我也刚刚进行了一个小的基本数字检查,以确保输入的值是一个数字(注意所有输入都会产生一个字符串),但只是检查是否输入了一个数字 - 在使用 parseFloat 解析它之后- 将它乘以 1 并将新值与输入值进行比较 - 如果不相同 - 它不是数字。

我还弹出了一个清除文本描述的方法,以及当要在输入框中输入新值时 - jus cos' :)

function roundNumber(){
  var num = parseFloat(document.getElementById('numberInput').value);
  if(num * 1 !== num) {
    document.getElementById('numberDisplay').innerText = 'Not a Valid Number - try again';
    document.getElementById('numberInput').value = '';
  } else {
   var numRounded = (Math.round(num*10)/10).toFixed(1);
   document.getElementById('numberDisplay').innerText = 'Rounded number:   '+ numRounded;
   }
}

function clearText(){
  document.getElementById('numberInput').value = '';
  document.getElementById('numberDisplay').innerText = '';
 }
<input type="text" id="numberInput" onclick="clearText()"/>
<button type = "button" id="inputButton" onclick="roundNumber()">Round Value</button>
<p id = "numberDisplay"><p>

关于javascript:如何将数字四舍五入到最接近的 10 美分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43164228/

相关文章:

javascript - 如果我使用 www,我可以从子域访问 iframe 的内容吗?在主域?

javascript - 如何在不提交表单的情况下按回车键单击按钮

javascript - 矩形图() : is the documentation wrong?

javascript - django ajax多表单提交

javascript - 在 mvc 中回发后自动完成不起作用

javascript - 如何在 Vue.js 中从 JSON 数据创建 select 元素?

javascript - jQuery 根据正则表达式获取 css 属性

javascript - 将简单的 Perl 脚本翻译成 Python 以向客户端发送响应?

javascript - 如何获取我选中的复选框的 ID?

javascript - KendoGrid分页有 "undefined"和 "NaN"