math - JavaScript: Trim .toPrecision() trailing zeros -


i creating online calculator using javascript.

i have work out calculation:

eval(expression).toprecision(10); 

this produces right output in cases. e.g.

eval('456456+45646486*45646884').toprecision(10) // output: "2.083619852e+15"  eval('1/0').toprecision(10) // output: "infinity" 

however

eval('4*1').toprecision(10) // output: "4.000000000" 

how trim trailing zeros but keep nice outputs above?

only all-zero decimals

  eval('4*1').toprecision(10).replace(/\.0+$/,"") 

zero ending decimals:

  eval('4.5*1').toprecision(10).replace(/\.([^0]+)0+$/,".$1") 

edit: handle both 0 , ending 0 cases

edit: if use .toprecision() first, , have ".", can trim off trailing zeros:

  eval('4.5*1').toprecision(10).replace(/0+$/,"") 

edit: handling trailing decimals:

eval('4.5*0').toprecision(10).replace(/\.?0+$/,"") 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

qt - Errors in generated MOC files for QT5 from cmake -