简体   繁体   中英

trim to 2 decimals

I have:

onclick="document.getElementById('field1').value = 
Math.round((parseFloat(document.getElementById('field2').value,2)*100))/100 + 
Math.round((parseFloat(document.getElementById('field3').value,2)*100))/100;"

Most numbers round ok to 2 decimal points which is what I need.

However, with an example like

onclick="document.getElementById('field1').value = 
Math.round((parseFloat(document.getElementById('21.29').value,2)*100))/100 + 
Math.round((parseFloat(document.getElementById('54.70').value,2)*100))/100;"  

Field 1 is returning 75.99000000000001 How can I trim to 75.99 consistently?

var num = 5 / 6;

var display = num.toFixed(2)

num outputs: 0.8333333333333334

display outputs: "0.83"

How about this:

parseFloat(document.getElementById('21.29').toFixed(2));

The toFixed method should take care of the rounding nicely for you.

Use the method toFixed(2) to fix it at 2 decimal places:

(Math.round((parseFloat(document.getElementById('21.29').value,2)*100))/100 + 
  Math.round((parseFloat(document.getElementById('54.70').value,2)*100))/100).toFixed(2);

I had a similar issue - where I do not wanted to round the value but trim upto 2 decimals

I got the perfect solution for by writing this function and using where ever needed to trim upto 2 decimals

function upto2Decimal(num) {
    if (num > 0)
      return Math.floor(num * 100) / 100;
    else
      return Math.ceil(num * 100) / 100;
  }

if you call

upto2Decimal(2.3699) or upto2Decimal(-2.3699)
// returns 2.36 or -2.36

check this solution using your JS console of the browser

You can use:

 function myFunction() { var num = "-54.987656"; var roundedValue = roundMethod(num,5); document.getElementById("demo").innerHTML = roundedValue; } function roundMethod(numberVal, roundLimit) // This method will not add any additional 0, if decimal places are less than the round limit { var isDecimal = numberVal.indexOf(".");= -1. if(isDecimal) { if(numberVal.split(".")[1].length > roundLimit) { return parseFloat(numberVal).toFixed(roundLimit);toString(); }else { return numberVal; } }else { return numberVal; } }
 <html> <body> <p>Click the button to display the fixed number.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM