But what if we’d like to round the number to n-th digit after the decimal?įor instance, we have 1.2345 and want to round it to 2 digits, getting only 1.23.įor example, to round the number to the 2nd digit after the decimal, we can multiply the number by 100, call the rounding function and then divide it back.Īlert( 0.1 + 0.2 ) // 0.30000000000000004 These functions cover all of the possible ways to deal with the decimal part of a number. Here’s the table to summarize the differences between them: unc (not supported by Internet Explorer) Removes anything after the decimal point without rounding: 3.1 becomes 3, -1.1 becomes -1. Math.round Rounds to the nearest integer: 3.1 becomes 3, 3.6 becomes 4, the middle case: 3.5 rounds up to 4 too. Math.ceil Rounds up: 3.1 becomes 4, and -1.1 becomes -1. There are several built-in functions for rounding: Math.floor Rounds down: 3.1 becomes 3, and -1.1 becomes -2. One of the most used operations when working with numbers is rounding. And if we place one more dot, then JavaScript knows that the decimal part is empty and now goes the method.Īlso could write (123456).toString(36). If we placed a single dot: 123456.toString(36), then there would be an error, because JavaScript syntax implies the decimal part after the first dot. If we want to call a method directly on a number, like toString in the example above, then we need to place two dots. Please note that two dots in 123456.toString(36) is not a typo.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |