Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

javascript - JavaScript Integer除法导致浮点数,可能会舍入错误吗?(JavaScript Integer division resulting in float, is rounding error possible?)

I know that examples such as 1.005*100 / 100 produce a slightly inaccurate result (100.49999999999999) in JavaScript, and this is intrinsic to floating point design.

(我知道例如1.005*100 / 100 100/100之类的示例在JavaScript中产生的结果有点不准确(100.49999999999999),这是浮点设计所固有的。)

My question is to see whether I can produce a reliable decimal round routine without the use of string manipulation.

(我的问题是看是否可以在不使用字符串操作的情况下生成可靠的十进制舍入例程。)

Where x is an integer, will x / 100 (int/int=float) ever produce a visual inaccuracy?

(如果x是整数, x / 100 (int / int = float)会不会产生视觉误差?)

(ie ..000001 or ..99999 ) An example proving this would be preferable.

((即..000001..99999 )证明这一点的示例将是更可取的。)

If the answer is yes then the only way to reliably move the decimal point towards the left in JavaScript is with string manipulation (ie MDN's Math.round10 ), and to take the modest performance hit involved.

(如果答案是肯定的,那么可靠地将小数点向JavaScript中的左侧移动的唯一方法是使用字符串操作(即MDN的Math.round10 ),并避免影响性能。)

  ask by Bryan Field translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to this test, there are no inaccuracies from division of integers by integers.

(根据该测试,将整数除以整数没有任何误差。)

 var multipliers = [10, 100, 1000, 10000, 100000, 1000000] for(var i = 0; i < 100000; i++) { multipliers.forEach(function (mul) { var x = i / mul if(x != x.toFixed(6)) document.write('found one! ' + i + ' / ' + mul + ' = ' + x + '<br/>') }) } document.write('done!') 

Nice.

(真好)

This means a robust round-to-decimal routine can be created without string manipulation.

(这意味着无需字符串即可创建健壮的舍入到十进制例程。)

:-)

(:-))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...