简体   繁体   中英

Floating point number precision in JavaScript

I want to use some formula, but I can't deal with the result, decimal point uncontrollable.

if I set W.value=30 R.value= 1

          let endresult = 
           Math.round(((W*(36/(37 - R)))+
          (W*(1 + 0.0333 * R))+
          ((100 * W)/(101.3 - 2.67123*R))+
          (W* (Math.pow(R,0.1)))+
          ( (100 * W)/(52.2 +(41.9 *(Math.pow(2.71828,-0.055*R)))))+
          (W*(1 + 0.025 * R))+ 
          ((100 * W)/(48.8 + (53.8 * 
          ((Math.pow(2.71828,-0.075*R)))))))/7)

          for(let i=0 ;i <6 ;i++){
          if(endresult<500 && endresult>0){
          let newul = document.querySelector('#newul')
          let newli = document.createElement('li')
          newli.id="result"
          let frag =document.createDocumentFragment()
          let newtext =document.createTextNode(`${"1RM "+ 
          (i+5)+"0%:"+endresult*(((i+5)*10)/100)+"kg"}`)
          frag.appendChild(newtext)
          frag.appendChild(newli)
          newul.appendChild(frag)
          }
          =
          1RM 50%:15.5kg
          1RM 60%:18.599999999999998kg     
          1RM 70%:21.7kg
          1RM 80%:24.8kg
          1RM 90%:27.900000000000002kg      
          1RM 100%:31kg

I don't want to have those extra decimal places, best can round the result, and I try to use "number-precision" / "Bignumber" to precise the result or Math.round, converted to String but still like a mess. It's any other way I can do?

You can use the JavaScript function toFixed(numberOfDecimals). See this

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