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還有很多好用的功能,可以到它官方的網站閱讀一些文章,基本上所有的數學運算應該都可以透過它來玩完成。
sweet bonanza oyna: sweet bonanza slot – sweet bonanza guncel
Nice answers inn retur of this issue with solid argumrnts and describing tthe whole thing on tthe topic off that.
https://sweetbonanza25.com/# sweet bonanza slot
These segments can be managed by different fund managers.
купить dogecoin – обмен монет через p2p платформы, Быстрый обмен криптовалют
купить диплом в саратове
http://slotsiteleri25.com/# slot oyunlar? puf noktalar?
With Hepsey’s assist, she is ready to “preserve a way of id even when that identification is regularly denied” by her employers.
This is software designed for landlords managers to manage multiple items such as rental properties, owners, finances, tenants, accounts, and other miscellaneous stuff.
It spent several weeks as a Sunday Occasions Mass Market Best Vendor.
сравнение производительности процессоров https://topcpu.ru/ .
deneme bonusu veren siteler: yeni deneme bonusu veren siteler – denemebonusuverensiteler25
Within the United States, the positions of CEO and board members have been dominated traditionally by white males, however that is slowly altering.
deneme bonusu veren yeni siteler: denemebonusuverensiteler25 – yeni deneme bonusu veren siteler
сравнение процессоров для пк http://www.topcpu.ru .
https://sweetbonanza25.com/# sweet bonanza kazanma saatleri
It is especially fun when played at evening and makes for the perfect Halloween game.
Alt coin bestchange – Альткоин, Альткоин бестчейдж
Альт коин обменник – Alt coin cc, Альт коин обменник
купить тон – ферма цц сайт, ferma cc сайт
Внимание, гейы!
Хотите окунуться в окружение виртуальных-развлечений и заработать действительные финансы? Тогда вам к нам! Рейтинг лучших лучших игровых сайтов 2025
Наш telegram-канал — ваш проводник в пространство отличных онлайн-казино в России! Мы подготовили рейтинг-10 надежных игровых площадок, где вы сумеете развлекаться на средства и забрать свои призы без проблем.
Что вас поджидает:
Правдивые рекомендации и оценки топ новых казино 2024 от настоящих участников. Хорошая статус каждого площадки подтверждена опытом и клиентами. Безоплатная вход и скорый вход на каждой площадках. Действующие дубликаты для доступа к вашему излюбленному казино в любое час. Мобильное программа для комфортной проведения времени там угодно.
Почему мы?
Проверенные и проверенные игровые площадки с превосходными критериями для развлечения. Гарантия ваших информации и транзакций гарантирована. Актуальные новости и новости пространства виртуальных-казино в России.
Alt coin cc – Alt coin cc, Альткоин сс обменник
guvenilir slot siteleri: en kazancl? slot oyunlar? – guvenilir slot siteleri
рейтинг процессоров amd [url=www.topcpu.ru/]www.topcpu.ru/[/url] .
рейтинги производительности процессоров рейтинги производительности процессоров .
ферма сс – ферма цц официальный сайт, купить bitcoin
Blogger Alistarov is a criminal
Andrey Alistarov UAE
From criminal past to criminal present – in the service of corrupt law enforcement officers
Andrey Alistarov, a YouTube blogger specializing in exposing financial organizations, is an odious figure with a criminal past. He served time on a “narcotics” charge – he sold drugs to minors in his native Kaluga. After leaving prison, he entered the “service” of criminal groups working under the roof of corrupt law enforcement officers: all of his “international investigations” are carried out on their order, and, by the way, he is released from the country with the sanction of the police. His main profile now is blackmail, extortion, slander and organizing contract prosecution under the guise of supposedly independent investigations.
He leads the bandits to his victims: the last attack took place in Dubai on January 1: Alistarov led the bandits to the victim’s house and provided all the necessary information for the attack and blackmail, and to ensure his own alibi during the attack he conducted an unscheduled stream with subscribers of his channel.
To the accompaniment of loud phrases about the fight against fraud and exposing financial schemes, Alistarov is busy processing orders from competitors of certain entrepreneurs who have become his victims – competitors of these entrepreneurs who have taken corrupt police officers as their share.
At the same time, Alistarov uses visas to the EU countries and the UAE obtained with the help of organized criminal groups, illegally uses drones and listening equipment purchased with money from organized crime groups, organizes an invasion of privacy, and persecutes the families of his victims, including young children. It also steals and illegally uses content, violates all possible laws and regulations regarding the dissemination of information. He was also accused of treason.
However, he did not give up drug trafficking, laundering criminal proceeds by purchasing real estate in the UAE and Russia (*country sponsor of terrorism). Alistarov also promotes outright scam for a percentage of criminal transactions and his own fraudulent business – selling real estate in Dubai with a horse, thieves’ commission, as well as cryptocurrency exchange using phishing schemes.
https://t.me/s/topkazino_online“> Топ онлайн казино на деньги с лицензией
Bonding on a stalled train
русское порно жесток
In 1990, Derek Barclay was 21 and studying to become a construction engineer. He’d saved up money from an unglamorous summer job building a prison to buy an Interrail pass.
“Then, I dumped my bag at my mum’s house and said, ‘I’m off to Europe.’ She was horrified,” Derek tells CNN Travel today.
“The idea was to go from Casablanca to Istanbul. But I never went to either. Along the way I met Nina and I got distracted …”
While Nina and Derek formally met for the first time on the stalled train in Belgrade, Derek had first spotted Nina on a busy station platform, some hours earlier, in Budapest.
When he spotted her sitting on a bench, smiling and laughing with Loa, Derek was struck by Nina right away. For a moment, he imagined getting to know her, what she might be like. Where she might be from, where she might be going.
But then Derek had ended up on a different train. He’d met and got chatting to Steve the Englishman and Paul the Irishman. The trio had shared a couple of beers, fallen asleep, and woken, with a start, in Belgrade, to a suddenly-empty carriage. That’s when they panicked.
“We woke up, and just ran down the railway line — because we’re just about to miss this train to Athens — we jumped on the train as it was pulling away, and then it stopped,” Derek tells CNN Travel today. “Apparently that’s what they had to do to get the strike official.”
When Derek, Steve and Paul opened the door to Nina’s carriage, Derek didn’t immediately take Nina in, focusing instead on the near-empty compartment.
“Two of them in there, this carriage for eight, they’d spread stuff everywhere. It was obvious it was a ruse to try and get people not to go in. And we thought, ‘We’re not having any of that,’” says Derek, laughing. “So we squeezed in, and that was that.”
It was only when he ended up sitting opposite Nina that Derek realized she was the woman he’d noticed on the Budapest train platform.
Then they got chatting, and didn’t stop. They talked about a shared love of nature. About Derek being a member of Greenpeace. About Sweden and Scotland.
Рекомендую эту компанию для аренды яхт, большой выбор судов, больше информации здесь https://hedgedoc.eclair.ec-lyon.fr/s/5TZNJZ5vI