JavaScript Math trunc() method - JavaScript Tutorial

JavaScript Math trunc() method

BLUF: This tutorial on JavaScript Math trunc() method provides an in-depth look at JavaScript's core features. It includes practical examples and code snippets to help you master modern JS development.
Key Discovery: JavaScript Math trunc() method

Understanding JavaScript Math trunc() method is crucial for building dynamic, interactive web applications. Explore the examples below to see it in action.

The trunc method in JavaScript is designed to eliminate the decimal portion of a specified number, returning solely the integer part that remains.

Syntax

The trunc function can be expressed using the following syntax:

Example

Math.trunc(num)

Parameter

num - A number.

Return

The integer part of the given number.

JavaScript Math trunc method example

In this section, we will explore the trunc method by examining a variety of examples.

Example 1

Consider the following example that demonstrates how to extract and display the integer portion of specified numbers.

Example

<script>

document.writeln(Math.trunc(12.24)+ "<br>");

document.writeln(Math.trunc(0.84));

</script>

Output:

Example 2

In this illustration, we will demonstrate the use of the trunc function with negative integers.

Example

<script>

document.writeln(Math.trunc(-12.24)+ "<br>");

document.writeln(Math.trunc(-0.84));

</script>

Output:

Output

-12

0

Example 3

In this section, you have the opportunity to evaluate the trunc method using your own custom test scenarios.

Example

<script>

function display()

{

  var x=document.getElementById("num").value;

document.getElementById("result").innerHTML=Math.trunc(x);

}

</script>

<form>

  Enter a number: <input type="text" id="num">

  <input type="button"  onclick="display()" value="submit">

  </form>

  <p><span id="result"></span></p>

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience