查看此代码:
function testprecision(){
var isNotNumber = parseFloat('1.3').toPrecision(6);
alert(typeof isNotNumber); //=> string
}
我会期待一个数字。如果 'isNotNumber' 应该是一个实数,重铸是解决方案:
alert(typeof parseFloat(isNotNumber)) //=> number
[编辑] 感谢您的回答。我得出的结论是,精度并不是那么精确。它可以表示一个数字的总位数,也可以表示小数位数。荷兰(我来自哪里)的大多数人都以“小数位数”的方式考虑精度。javascript toPrecision 方法涉及第一个表示,所以这很混乱。无论如何,该方法可以引入“错误精度”,对吗?对于我们必须固定的第二个含义,同样如此(返回字符串,错误精度的可能性)。
无论如何,在将重新发明轮子作为我的主要爱好后,我使用我在这里收集的知识来构建一个 javascript 浮动对象。也许它对外面的人有用,或者你们中的一个人有更好的想法?
function Float(f,nDec) {
var Base = this,val;
setPrecision( nDec || 2 );
set( f || 0, nDec || Base.precision );
Base.set = set;
Base.ndec = setPrecision;
/** public setprecision
* sets a value for the number of fractional
* digits (decimals) you would like getf to
* return. NB: can't be more than 20.
* Returns the Float object, so allows method
* chaining
* @param {Number} iPrecision
*/
function setPrecision(iPrecision) {
var ix = parseInt(iPrecision,10) || 2;
Base.precision = ix >= 21 ? 20 : ix;
return Base;
}
/** public set
* sets the 'internal' value of the object. Returns
* the Float object, so allows method chaining
* @param {Number} f
* @param {Number} ndec
*/
function set(f,ndec) {
val = parseFloat(f) || 0;
if (ndec) { setPrecision(ndec); }
Base.val = val;
return Base;
}
/** public get:
* return number value (as a float)
*/
Base.get = function(){
var ndec = Math.pow(10,Base.precision),
ival = parseInt(val*ndec,10)/ndec;
Base.val = ival;
return Base.val;
};
/** public getf
* returns formatted string with precision
* (see Base.setPrecision)
* if [hx] is supplied, it returns
* the float as hexadecimal, otherwise
* @param {Boolean} hx
*/
Base.getf = function(hx){
var v = Base.val.toFixed(Base.precision);
return hx ? v.toString(16) : v;
};
/** public add
* adds [f] to the current value (if [f] is a
* Float, otherwise returns current value)
* optionally sets a new number of decimals
* from parameter [ndec]
* @param {Number} f
* @param {Number} ndec
*/
Base.add = function(f,ndec){
if ( parseFloat(f) || val===0) {
set(Base.val+parseFloat(f));
if (ndec) { setPrecision(ndec);}
}
return Base.get();
};
/** toString
* returns the internal value of the Float object
* functions like a getter (supposedly)
*/
Base.toString = Base.get;
}
用法/示例:
var xf = new Float(); //=> value now 0.0
xf.set(0.86/0.8765,17).add(3.459);
alert(xf+'|'+xf.getf()); //=> 4.440175128351398|4.44017512835139800