Javascript的數學難題
首先先考大家幾個數學題,如果這幾題的答案你都能順利的回答,那恭喜你!你可以安心地閱讀這篇文章,你一定能看懂!
題目ㄧ. 0.1 + 0.2 = ?
題目二. 1 – 0.9 = ?
題目三. 0.69 x 10 = ?
相信上面三個簡單的十進位數學運算,你的答案應該會跟我一樣吧?
第一題. 0.3
第二題. 0.1
第三題. 6.9
上面應該是無庸置疑的答案,但是如果我們把這三個題目丟給Javascript去運算之後,得到的結果會變成這樣:
第一題. 0.1 + 0.2 = 0.30000000000000004
第二題. 1 – 0.9 = 0.09999999999999998
第三題. 0.69 x 10 = 6.8999999999999995
什麼!?Javascript連這種小學生的算術都會算錯嗎?其實是有原因的,Javascript所有數字都是以64位浮點數形式儲存,也就是所有的數字都會變轉換成二進位。
上面題目中特別有提到這是3個十進位的數學運算,這也就是這個題目的重點,如果今天的題目改成:10 / 3 = 3.3333333333333334 也許你就能比較明白了,也就是說在十進位中要表達 1 / 3 和二進位中表達 1 / 10 一樣困難。
但其實在我們設計網頁的過程中,使用者是沒有二進位觀念的,只在乎運算出來的數值是否符合十進位的結果,這個時候我們可以利用一些技巧來達成正確的結果。
方法1 . 將小數變成整數後再進行運算
第一題. ((0.1 x 10) + (0.2 x 10)) / 10 = 0.3
第二題. ((1 x 10) – (0.9 x 10)) / 10 = 0.1
第三題. ((0.69 x 100) x 10 / 100) = 6.9
雖說以上的方法能夠順利完成任務,但若運算的數值是動態(Dynamic)的,乘數的部分就比較難下,所以我們可以採用第二種方法。
方法2. Math.js(https://mathjs.org/)
透過網站上提供的js,或是透過CDN(https://cdnjs.com/libraries/mathjs)來引入後,透過以下的方法,就可以正確計算出上面三個題目的結果,其中14指的是精準度,通常已經很夠用了。
第一題. math.format(0.1 + 0.2 , 14) = 0.3
第一題. math.format(1 – 0.9 , 14) = 0.1
第一題. math.format(0.69 x 10 , 14) = 6.9
其實Math.js還有很多好用的功能,可以到它官方的網站閱讀一些文章,基本上所有的數學運算應該都可以透過它來玩完成。
purple pharmacy mexico price list: mexican online pharmacies prescription drugs – mexican pharmaceuticals online
Федеральный закон https://zakonobosago.ru “Об обязательном страховании гражданской ответственности владельцев транспортных средств” (ОСАГО)
mexican rx online: mexican drugstore online – mexican mail order pharmacies
Привет, друзья!
Заказать документ университета вы сможете в нашей компании.
asxdiplomik.com/kupit-diplom-o-vysshem-obrazovanii
Review my page … Find top-rated certified Daycares in your area
Здравствуйте!
Заказать диплом о высшем образовании.
sonnick84.collectblogs.com/73879610/%D0%A1%D0%BE%D0%B2%D0%B5%D1%82%D1%8B-%D1%8D%D0%BA%D1%81%D0%BF%D0%B5%D1%80%D1%82%D0%B0-%D0%BA%D0%BE%D1%82%D0%BE%D1%80%D1%8B%D0%B5-%D0%BF%D0%BE%D0%BC%D0%BE%D0%B3%D1%83%D1%82-%D0%B1%D1%8B%D1%81%D1%82%D1%80%D0%BE-%D0%BF%D1%80%D0%B8%D0%BE%D0%B1%D1%80%D0%B5%D1%81%D1%82%D0%B8-%D0%B4%D0%BE%D0%BA%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B
Привет, друзья!
Легальные способы покупки диплома о среднем полном образовании
mandiplomiks.ru
Здравствуйте!
Мы изготавливаем дипломы любой профессии по доступным ценам.
norbrookequity.com/купить-надежный-диплом
Привет, друзья!
Купить документ о получении высшего образования
diploms-x.com/kupit-diplom-sankt-peterburg
pharmacies in mexico that ship to usa best online pharmacies in mexico mexican mail order pharmacies
Добрый день!
Полезная информация как купить диплом о высшем образовании без рисков
landik-diploms-srednee.ru/attestat-shkoly
Complaints have flooded social media since the video’s release, with residents saying it fails to show the modern side of their country. Many claim the footage was edited to seemingly appear old-fashioned, with a faded sepia tone, and that the camera focuses on shabby architecture.
жесткое групповое порно
Others have complained about the video’s airport scenes, during which one of the characters loses his luggage and seeks help from a local ground staff member called “Happy.”
“When I watched it, I was thinking, this was Thailand 50 years ago. This looked like Thailand 70 years ago. There were no segments showing the modernity of my home,” David William, an American content creator based in Thailand, said in Thai in a TikTok video that has been viewed over 11 million times.
In an interview with CNN, he said he’s never seen “a cab that looked that bad before” in his nearly 10 years in the country, adding Thailand’s main gateway, Suvarnabhumi Airport is just as modern as New York’s John F. Kennedy International Airport.
“Thailand is a modern, safe and beautiful country,” he said. “I just hope don’t misunderstand.”
Echoing his view, Facebook user Nipawan Labbunruang said the video makes Thailand look “terrible.”
“What is this clip trying to present?” she wrote in a post that received 1,900 likes.
mexican mail order pharmacies: reputable mexican pharmacies online – mexican rx online
Complaints have flooded social media since the video’s release, with residents saying it fails to show the modern side of their country. Many claim the footage was edited to seemingly appear old-fashioned, with a faded sepia tone, and that the camera focuses on shabby architecture.
пидар
Others have complained about the video’s airport scenes, during which one of the characters loses his luggage and seeks help from a local ground staff member called “Happy.”
“When I watched it, I was thinking, this was Thailand 50 years ago. This looked like Thailand 70 years ago. There were no segments showing the modernity of my home,” David William, an American content creator based in Thailand, said in Thai in a TikTok video that has been viewed over 11 million times.
In an interview with CNN, he said he’s never seen “a cab that looked that bad before” in his nearly 10 years in the country, adding Thailand’s main gateway, Suvarnabhumi Airport is just as modern as New York’s John F. Kennedy International Airport.
“Thailand is a modern, safe and beautiful country,” he said. “I just hope don’t misunderstand.”
Echoing his view, Facebook user Nipawan Labbunruang said the video makes Thailand look “terrible.”
“What is this clip trying to present?” she wrote in a post that received 1,900 likes.
purple pharmacy mexico price list: mexican pharmaceuticals online – reputable mexican pharmacies online
Привет!
Мы изготавливаем дипломы любой профессии.
moust.lv/read-blog/222_pochemu-na-poryadok-deshevle-i-proshe-zakazat-diplom-universiteta
Рады оказать помощь!.
mexican rx online mexican pharmaceuticals online buying prescription drugs in mexico
medicine in mexico pharmacies: buying from online mexican pharmacy – mexican pharmaceuticals online
shipping a car across the country shipping a car across the country .
pharmacies in mexico that ship to usa: п»їbest mexican online pharmacies – mexican pharmaceuticals online
auto transport across country auto transport across country .
cross country vehicle shipping cross country vehicle shipping .
auto transport enclosed auto transport enclosed .
Привет, друзья!
Мы изготавливаем дипломы психологов, юристов, экономистов и прочих профессий по приятным тарифам.
itbitgroup.ru/legkiy-sposob-priobresti-diplom-onlayn
buying prescription drugs in mexico online mexico pharmacies prescription drugs mexico drug stores pharmacies
cross country auto shipping cross country auto shipping .
my blog post :: Daycare Near Me – Find The Best Daycares Near You
Привет, друзья!
Как быстро и легально купить аттестат 11 класса в Москве
gaiassulin.com/диплом-о-среднем-образовании-как-и-где
Окажем помощь!.
best enclosed car transport companies best enclosed car transport companies .
My page craiglistforsex