Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Fix Uncaught ReferenceError: $ is not defin... >>
<< How to Check for a Hash (#) in a URL using JavaScr...