[英]How to fill two floats to precision of one of them?
I have two numbers, for example:我有两个数字,例如:
var a = $('input#number_1').val(); // 12;
var b = $('input#number_2').val(); // 0.01;
How to fill a to precision of b?如何填充a到b的精度?
a: 12.01
b: 0.01
or fill both to for example:或填写两者,例如:
a: 12.0000
b: 0.0100
Edit:编辑:
var a = parseFloat($('input#number_1').val()); // 12;
var b = parseFloat($('input#number_2').val()); // 0.01;
The first thing to realize is that in your code, a
and b
are strings , not numbers.首先要意识到的是,在您的代码中,
a
和b
是字符串,而不是数字。
What you could do is convert them both to number, the do a simple toString
, find out how many digits are after the .
你可以做的是将它们都转换为数字,做一个简单的
toString
,找出.
in each of them, and then use the larger of those numbers with toFixed
on the numbers (which lets you say how many places after the decimal you want).在每个数字中,然后使用这些数字中较大的一个,并在数字上使用
toFixed
(它可以让您说出您想要的小数点后多少位)。
For example:例如:
var a = $('input#number_1').val(); var b = $('input#number_2').val(); // Convert them to numbers var aValue = +a; var bValue = +b; // Find out which has more digits after the decimal var maxDigits = 0; var n; a = String(aValue); n = a.indexOf('.'); if (n !== -1) { maxDigits = a.length - n - 1; } b = String(bValue); n = b.indexOf('.'); if (n !== -1) { maxDigits = Math.max(b.length - n - 1, maxDigits); } // Convert back to strings with that many of digits a = aValue.toFixed(maxDigits); b = bValue.toFixed(maxDigits); // Put them back in the fields if that's what you want $('input#number_1').val(a); $('input#number_2').val(b);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input id="number_1" value="12"> <input id="number_2" value="0.01">
try this javascript toFixed function, which is used for fix decimal value .试试这个 javascript toFixed 函数,它用于修复十进制值。 you can set number of decimal value to function.
您可以设置十进制值的数量以发挥作用。 make sure what you are passing.
确保你正在通过什么。 you may change it as per your requirement,
您可以根据您的要求更改它,
var num = 5; var n = num.toFixed(2) alert(n); num = 5.6785; n = num.toFixed(2) alert(n);
Refrence: http://www.w3schools.com/jsref/jsref_tofixed.asp参考: http : //www.w3schools.com/jsref/jsref_tofixed.asp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.