Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

javascript - parseFloat rounding

I have javascript function that automatically adds input fields together, but adding numbers like 1.35 + 1.35 + 1.35 gives me an output of 4.050000000000001, just as an example. How can I round the total to the second decimal instead of that long string?

The input fields will have more than just the 1.35 example so I need the total to never have more than 2 points after the decimal. Here is the full working code:

<html>
<head>
<script type="text/javascript">
function Calc(className){
var elements = document.getElementsByClassName(className);
var total = 0;

for(var i = 0; i < elements.length; ++i){
total += parseFloat(elements[i].value);
}

document.form0.total.value = total;
}

function addone(field) {
  field.value = Number(field.value) + 1;
  Calc('add');
}
</script>
</head>
<body>
<form name="form0" id="form0">
1: <input type="text" name="box1" id="box1" class="add" value="0" onKeyUp="Calc('add')" onChange="updatesum()" onClick="this.focus();this.select();" />
<input type="button" value=" + " onclick="addone(box1);">
<br />

2: <input type="text" name="box2" id="box2" class="add" value="0" onKeyUp="Calc('add')" onClick="this.focus();this.select();" />
<input type="button" value=" + " onclick="addone(box2);">
<br />

<br />
Total: <input readonly style="border:0px; font-size:14; color:red;" id="total" name="total">
<br />
</form>
</body></html>

Some things I have tried, which should work but I am clearly implementing them incorrectly:

for(var i = 0; i < elements.length; ++i){
total += parseFloat(elements[i].value.toString().match(/^d+(?:.d{0,2})?/));

var str = total.toFixed(2);

or

for(var i = 0; i < elements.length; ++i){
total += parseFloat(elements[i].value * 100) / 100).toFixed(2)

Have also had no luck with Math.floor

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use toFixed() to round num to 2 decimal digits using the traditional rounding method. It will round 4.050000000000001 to 4.05.

num.toFixed(2);

You might prefer using toPrecision(), which will strip any resulting trailing zeros.

Example:

1.35+1.35+1.35 => 4.050000000000001
(1.35+1.35+1.35).toFixed(2)     => 4.05
(1.35+1.35+1.35).toPrecision(3) => 4.05

// or...
(1.35+1.35+1.35).toFixed(4)     => 4.0500
(1.35+1.35+1.35).toPrecision(4) => 4.05

Reference: JavaScript Number Format - Decimal Precision


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...