parseFloat或toFixed不代表小数

时间:2018-06-19 18:02:47

标签: javascript

用toFixed和parseFloat构建一个代表数字的计算器,它似乎忽略了十进制键入,并且在您正确使用“”时也是如此。或“ .0”或“ .00”等。它会跳过,直到您输入非0的数字为止。有帮助吗?

var ghost = Number(parseFloat(reactant).toFixed(13));
var ghost2 = Number(parseFloat(reactant2).toFixed(13));
var ghostspec = Number(parseFloat(reactantspec).toFixed(13));

 if (vi === 0){
    document.getElementById('result').innerHTML = ghost;
} else if (vi >= 1 && tx === 0) {
    document.getElementById('result').innerHTML = ghost2;
} else if (vi >= 1 && tx > 0) {
    document.getElementById('result').innerHTML = ghostspec;
}
}
  **this is how you type decimals**
      function click10() {
    if (vi === 0) {
   click10a();
} else if (vi !== 0 && tx === 0) {
   click10b();
 } else if (vi !== 0 && tx !== 0) {
    if (di3 === 0) {
        virs++;
        reactantspec = reactantspec + "" + ".";
        di3++;
    }
}
}
function click10a() {
    if (di1 === 0) {
    reactant = reactant + "" + ".";
    vir++;
    di1++;
    }
}
function click10b() {
    if (di2 === 0) {
    reactant2 = reactant2 + "" + ".";
    vir2++;
    vi++;
    di2++;
   }
}

1 个答案:

答案 0 :(得分:0)

“问题”是Number函数会截断parseFloat(...).toFixed(13)生成的格式化数字(字符串)的小数。看看:

let wn = Number( parseFloat( "1" ).toFixed(13) ) + "</br>" +
         Number( parseFloat( "1." ).toFixed(13) ) + "</br>" +
         Number( parseFloat( ".1" ).toFixed(13) ) + "</br>" +
         Number( parseFloat( "1.1" ).toFixed(13) ) + "</br>" +
         Number( parseFloat( "0" ).toFixed(13) ) + "</br>" +
         Number( parseFloat( "0." ).toFixed(13) ) + "</br>" +
         Number( parseFloat( ".0" ).toFixed(13) ) + "</br>" +
         Number( parseFloat( "0.0" ).toFixed(13) );

let wtn = parseFloat( "1" ).toFixed(13) + "</br>" +
          parseFloat( "1." ).toFixed(13) + "</br>" +
          parseFloat( ".1" ).toFixed(13) + "</br>" +
          parseFloat( "1.1" ).toFixed(13) + "</br>" +
          parseFloat( "0" ).toFixed(13) + "</br>" +
          parseFloat( "0." ).toFixed(13) + "</br>" +
          parseFloat( ".0" ).toFixed(13) + "</br>" +
          parseFloat( "0.0" ).toFixed(13);

document.getElementById( "result" ).innerHTML = 
       "With Number(...):</br>" + wn + "</br></br>" + 
       "Without Number(...):</br>" + wtn;
<div id="result"></div>