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還有很多好用的功能,可以到它官方的網站閱讀一些文章,基本上所有的數學運算應該都可以透過它來玩完成。
farmaci senza ricetta elenco: Cialis generico farmacia – migliori farmacie online 2024
ВНЖ Испании ВНЖ Испании .
https://skachat-pinup-uz.website/
Привет, друзья!
Купить диплом о среднем полном образовании, в чем подвох и как избежать обмана?
mans-diplomyxx.ru/kupit-diplom-novosibirsk
Поможем вам всегда!.
Farmacia online piГ№ conveniente: kamagra – acquistare farmaci senza ricetta
farmacia senza ricetta recensioni: viagra senza prescrizione – viagra 100 mg prezzo in farmacia
http://kamagrait.pro/# top farmacia online
Farmacie online sicure: super kamagra – Farmacia online miglior prezzo
https://viagragenerico.site/# viagra originale in 24 ore contrassegno
Привет!
Мы изготавливаем дипломы психологов, юристов, экономистов и прочих профессий по невысоким тарифам.
rushkadiplomik.ru/diplom-o-srednem-tehnicheskom-obrazovanii
viagra generico recensioni: viagra online – viagra naturale in farmacia senza ricetta
Fafabet South Africa
fafabet south africa
Step into the thrilling universe of Fafabet’s casino, a place pulsating with excitement and brimming with opportunities for big wins! Whether you’re a seasoned gambler or a curious newcomer, this review will guide you through the vibrant selection of top-tier games, enticing bonuses, effective strategies, and seamless mobile play. Get ready to transform your gaming experience and discover why Fafabet is the go-to destination for online casino enthusiasts!
Best Casino Games at Fafabet
brings the excitement of a real casino directly to your screen, featuring a curated selection of games that cater to both new and seasoned players. The focus on popular games such as roulette, blackjack, and poker ensures a varied and engaging experience, providing options for strategic play, quick wins, and everything in between. This selection is not just about variety; it’s tailored to enhance player engagement and retention. The inclusion of games with different levels of complexity and reward strategies meets the diverse needs and preferences of the global online gambling community, making Fafabet a top choice for live casino enthusiasts.
Choose Your Game: Online Roulette, Blackjack, Poker
The heart of Fafabet’s live casino lies in its comprehensive offering of classic games, which are among the most popular and enduring in the gambling world. Let’s focus on the star of the casino floor: Roulette. This game not only attracts players with its simplicity and elegance but also offers various versions to suit different tastes and betting styles.
Jokabet Casino Espana: analisis completo (2024)
jokabet login
Introduccion a Jokabet Casino
Jokabet Casino ha emergido como una de las plataformas de juegos de azar en linea mas populares en Espana en 2024. Este analisis completo tiene como objetivo proporcionar una vision detallada de lo que ofrece este casino, desde su seguridad hasta sus juegos y promociones.
Jugar en Jokabet Casino: ?Es seguro y confiable?
Antes de aventurarte en el mundo de Jokabet Casino, es natural preguntarse sobre su seguridad. La plataforma esta licenciada y regulada por autoridades reconocidas, garantizando un entorno de juego seguro y justo para todos sus usuarios.
Los mejores bonos y promociones de Jokabet Casino
Bonos de bienvenida
ofrece generosos bonos de bienvenida para nuevos jugadores, incluyendo dinero extra y giros gratis. Con un bono Jokabet inicial, puedes empezar a explorar todas las oportunidades que este casino ofrece.
Promociones regulares
Los jugadores habituales pueden disfrutar de diversas promociones regulares, como bonos de recarga y torneos.
Programas de fidelidad
El programa de fidelidad de Jokabet recompensa a los jugadores leales con puntos que pueden canjearse por premios y beneficios exclusivos.
Feel free to visit my website … PokerTube – Watch Free Poker Videos & TV Shows
Benefits of mobile application
app pin-up casino
Today, it is very popular among gambling companies to create mobile applications for the users who use the phone the most. Many users download a pin-up program to take advantage of this program, which is the functionality of the browser version of the gambling platform.
If you decide to download the Pin-up mobile application, you can use this application. The company’s employees care about the comfort of their users. The program has many fans from the world of gambling. The company has worked hard to develop the program.
the profit
intuitive interface;
attractive design;
Various sporting events and gambling entertainments;
high speed of application;
economical use of Internet traffic;
Fixed access to the application, unlike the browser version.
where to download apps for android
There are several ways to download a pin-up program:
The download file is downloaded directly from the official website of the virtual gambling company. This is the safest and most reliable method because you do not need to be afraid of scammers when downloading from the site;
It is also recommended to download programs from third-party sites, but first you need to make sure that it is the original file, as scammers can offer you the wrong file.
Downloading the file is very fast and simple, even the most inexperienced user can easily install this program. On the official website of the company there are detailed instructions on how to install the file on Android.
Boost kasiino – ametlik kodulehekulg Eestis: taielik ulevaade
big boost casino
on Eesti mangurite seas kiiresti populaarsust kogunud. Kaesolevas artiklis vaatleme, miks Boost casino eesti on saavutanud sellise edu, kasitledes selle peamisi funktsioone ja pakutavaid teenuseid, sealhulgas manguvalikuid, boonuseid ja kasutajasobralikku liidest.
Boostcasino Mangude Ulevaade
Boost Casino pakub laia valikut ponevaid mange, mis meeldivad igale mangijale, alates algajatest kuni kogenud hasartmangusopradeni. Selles jaotises saate teada, milliseid erinevaid mange Boost Casino pakub, sealhulgas populaarseid manguautomaate ja lauamange, samuti live-kasiino voimalusi, mis pakuvad mangijatele toelist kasiinokogemust mugavalt oma kodus.
Slotid ja Lauamangud
Boost Casino’s on esindatud sadu slotimange erinevatelt arendajatelt, nagu NetEnt, Microgaming ja Play’n GO, mis tagab kvaliteetsed graafikad ja sujuva mangukogemuse. Lisaks klassikalistele slotidele leidub laialdaselt lauamange, sealhulgas:
1. Blackjack: Mitu varianti, nagu klassikaline, Euroopa ja Vegas Strip.
2. Rulett: Euroopa, Ameerika ja Prantsuse rulett.
3. Baccarat: Punto Banco ja kiire tempo baccarat.
Nende mangude RTP (Return to Player) maarad on tavaliselt vaga konkurentsivoimelised, mis tostab mangijate voiduvoimalusi. Boost Casino uuendab regulaarselt oma mangude valikut, pakkudes uusi ja ponevaid variante.
Привет!
Купить документ института вы сможете в нашей компании.
rushkas-diplom.ru
ISIS-inspired suspect planned suicide attack at Taylor Swift concert, Austrian authorities say
1xbet promo code free spins
Police in Austria have questioned three teenagers suspected of plotting a suicide attack at a Taylor Swift show, sparking renewed concerns over the indoctrination of young people online.
Foreign intelligence agencies helped authorities uncover the alleged scheme, according to the country’s Interior Minister Gerhard Karner. A source familiar told CNN that the US issued a warning to authorities in Vienna.
Organizers canceled three concerts, which were scheduled to take place in the European capital from Thursday to Saturday. CNN has reached out to Swift’s representatives for comment.
Investigators unearthed a stockpile of chemicals, explosive devices, detonators and 21,000 euros in counterfeit cash at the home of the main suspect, a 19-year-old ISIS sympathizer who had been radicalized online, according to authorities.
The young man – who was arrested Wednesday morning in the eastern town of Ternitz – planned to kill himself and “a large number of people,” according to the head of the domestic intelligence agency, Omar Haijawi-Pirchner.
“He said he intended to carry out an attack using explosives and knives,” Haijawi-Pirchner told reporters in Vienna on Thursday. “His aim was to kill himself and a large number of people during the concert, either today or tomorrow.”
Two other suspects were detained, aged 17 and 15. The 17-year-old worked for a facilities company that would have provided services at the concert venue. He was near the stadium when he was arrested and had recently broken up with his girlfriend, according to Haijwai-Pirchner.
Little has been revealed about the 15-year-old. Prosecutors will decide later if he was a witness or directly involved in the alleged plot.
The three are all Austrian-born with either Turkish, North Macedonian or Croatian backgrounds.
A chainsaw amnesty is protecting the rainforest in Borneo
автодик
Borneo was once covered in lush, dense rainforests, but they are rapidly disappearing. The Southeast Asian island, roughly three times the size of the UK, has lost half its forest cover since the 1930s, destroying precious habitat for wildlife such as the critically endangered orangutan, as well as valuable carbon stores.
A non-profit called Health in Harmony (HIH) is asking farmers to hand in their chainsaws in return for money, and a chance to set up an alternative livelihood.
Borneo is divided between Indonesia, Malaysia and Brunei, and it is estimated that up to 10% of its land is taken up by industrial palm oil and logging operations. But deforestation isn’t just about large-scale tree clearance; some of those behind the logging are small-scale farmers, cutting trees as a sideline to make ends meet.
Buyback and healthcare
HIH launched its chainsaw buyback scheme in 2017, under the group’s Indonesian name, Alam Sehat Lestari (ASRI). Farmers who illegally log and sell the wood to timber companies are given around $200 for their chainsaws, as well as up to $450 in financial support for them to set up an alternative, sustainable livelihood, such as opening a shop, organic farming and even beekeeping.
The scheme also involves addressing the root causes of the problem. According to HIH, many of the farmers who turn to logging do so because they need the money for basics like healthcare.
“They live far from the healthcare clinics, and they see logging as a place where they can get quick cash,” explained Mahardika “Dika” Putra, conservation program manager at HIH. “If they need this amount of money, they cut this amount of trees.
“We asked what solutions they think they need to live in harmony with the forest and they said, ‘high quality, affordable healthcare, and training in organic farming.’”
farmacie online sicure: Cialis generico prezzo – farmacie online sicure
Betfair Casino Espana
betfair live casino
Si estas en la busqueda de un casino online en Espana que ofrezca fiabilidad, podria ser la opcion perfecta. Con licencia y cumpliendo con los mas altos estandares de seguridad, este casino destaca por su variada seleccion de juegos proporcionados por los mas renombrados desarrolladores a nivel mundial. Desde tragamonedas clasicas hasta envolventes juegos de casino en vivo, Betfair Casino se ha convertido en el destino favorito de numerosos jugadores espanoles. Descubre en nuestra resena por que Betfair Casino ha logrado captar la atencion de tantos usuarios y conoce en detalle las caracteristicas que lo hacen destacar en el sector.
Resena sobre Betfair Casino Espana
Betfair Casino se ha establecido firmemente en el mercado de juegos de azar espanol como una opcion de confianza para los entusiastas del casino online. Operado por Betfair Casino Limited, este sitio esta acreditado por la Comision de Juegos del Reino Unido y la Autoridad de Juegos de Malta, ofreciendo un ambiente de juego seguro y regulado. A continuacion, te proporcionamos informacion relevante sobre Betfair Casino en Espana.
Baji Live Casino Overview
baji live login
Every casino in the world claims that its uniqueness and originality are the reasons for their existence, but what makes Baji Live casino so special is its unique history and modern technologies. Baji Live Casino is not only a place where you can bet your money on games; it’s also a blending of technology and the user interface that altogether gives an unprecedented gaming experience.
History and Licensing
Baji Live Casino is licensed by the Curacao Gaming Commission, one of the most problematic and legitimate online casino licences in the world. Why they chose Curacao would do Columbus be the most peaceful and the most economically sound. The most important thing is the game poker license of Curacao. It has these kinds of features:
International Rights: Curacao’s gaming license is known for its honesty and transparency. It is accepted in many countries and is a legal way for operators to launch services into a wider spectrum of markets worldwide.
Regulation with Control: Baji Live Casino should stay according to a variety of the different regulations which are the part of the license such as game fairness, user data protection, and the conduct of responsible gaming and security measures.
Audits and Checks: An auditing team is responsible for conducting regular control procedures of the casino. They are bankrolled by eCOGRA, and their ultimate aim is to ensure casino compliance with convenient, fair play and user safety requirements.
Transaction Security: Curacao is the place where special attention is paid to the protection of financial transactions, which is essential to the safety and prevention of fraud among the players as well.
For additional access and to alleviate blockers, our website provides mirror URLs like baji live 365, baji live 999, and baji 888 live. By means of this service, users can make requests as though they are in an unrestricted area and carry out transactions. The whole system, also, gives a high level of trust and security to Baji Live Casino users, which of course makes it really attractive to everybody that wants to either learn or play at an online casino. The stick to such strict licensing standards is the evidence that Baji Live I not only manages, but it is also strengthening its image as a reliable and responsible gambling provider in the market.
https://viagragenerico.site/# alternativa al viagra senza ricetta in farmacia
migliori farmacie online 2024: kamagra oral jelly consegna 24 ore – migliori farmacie online 2024
Привет, друзья!
Как официально купить диплом вуза с упрощенным обучением в Москве
rushkadiplomik.ru
viagra naturale in farmacia senza ricetta: viagra generico – viagra generico sandoz
http://avanafil.pro/# top farmacia online
gel per erezione in farmacia: viagra generico – esiste il viagra generico in farmacia
comprare farmaci online con ricetta: Avanafil 50 mg – farmacia online piГ№ conveniente
Привет!
Полезные советы по безопасной покупке диплома о высшем образовании
diploms-man.ru/kupit-diplom-ekaterinburg
Рады помочь!.