WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES
Advertisements

How to Convert a Float Number to a Whole Number in JavaScript

Topic: JavaScript / jQueryPrev|Next

Answer: Use the JavaScript trunc() Method

You can use the trunc() method to get the integer part of a number by removing any fractional digits. This method was added in ECMAScript 6 and supported by the latest browsers such as Chrome, Firefox, Safari, Opera, and Edge browsers. Not supported in Internet Explorer.

Alternatively, you can also try other methods like floor(), ceil() and round() to round a number. Let's take a look at the following example to understand how it works:

  • <script>
  • console.log(Math.trunc(3.5));    // Prints: 3
  • console.log(Math.trunc(-5.7));   // Prints: -5
  • console.log(Math.trunc(0.123));  // Prints: 0
  • console.log(Math.trunc(-1.123)); // Prints: -1
  •  
  • console.log(Math.ceil(3.5));     // Prints: 4
  • console.log(Math.ceil(-5.7));    // Prints: -5
  • console.log(Math.ceil(9.99));    // Prints: 10
  • console.log(Math.ceil(-9.99));   // Prints: -9
  •  
  • console.log(Math.floor(3.5));    // Prints: 3
  • console.log(Math.floor(-5.7));   // Prints: -6
  • console.log(Math.floor(9.99));   // Prints: 9
  • console.log(Math.floor(-9.99));  // Prints: -10
  •  
  • console.log(Math.round(3.5));    // Prints: 4
  • console.log(Math.round(-5.7));   // Prints: -6
  • console.log(Math.round(7.25));   // Prints: 7
  • console.log(Math.round(4.49));   // Prints: 4
  • </script>

Related FAQ

Here are some more FAQ related to this topic:

Advertisements
Bootstrap UI Design Templates

Your Feedback:

We would love to hear from you, please drop us a line.