Javascript convert to float to int

9 Ways To Convert Float To Integer In JavaScript

The conversion of floating point numbers to integers is a common task when creating web applications.

Although there are numerous ways to do this in JavaScript, developers often know no other way than to use the Math object or the parseInt function.

The JavaScript Math object allows to perform mathematical tasks on numbers.

All available functions can be found here.

Math.ceil

Rounds number up to the next larger integer (remember that the negative number -10 is larger than -11):

// Positive Math.ceil(10.1); // 11 Math.ceil(10.5); // 11 Math.ceil(10.9); // 11 // Negative Math.ceil(-10.1); // -10 Math.ceil(-10.5); // -10 Math.ceil(-10.9); // -10

Math.floor

Rounds number down to the next smaller integer:

// Positive Math.floor(10.1); // 10 Math.floor(10.5); // 10 Math.floor(10.9); // 10 // Negative Math.floor(-10.1); // -11 Math.floor(-10.5); // -11 Math.floor(-10.9); // -11

Math.round

Rounds number to the nearest integer:

// Positive Math.round(10.1); // 10 Math.round(10.5); // 11 Math.round(10.9); // 11 // Negative Math.round(-10.1); // -10 Math.round(-10.5); // -10 Math.round(-10.9); // -11

Math.trunc

This function is an addition of ES6, earlier versions of JavaScript do not include it.

Returns the integer part of the number by removing any fractional digits:

// Positive Math.trunc(10.1); // 10 Math.trunc(10.5); // 10 Math.trunc(10.9); // 10 // Negative Math.trunc(-10.1); // -10 Math.trunc(-10.5); // -10 Math.trunc(-10.9); // -10

ParseInt

Parses a string argument and returns an integer of the specified radix.

The radix parameter is used to specify which number system is to be used. It is an integer between 2 and 36.

const radix = 10; // Positive parseInt("10.1", radix); // 10 parseInt("10.5", radix); // 10 parseInt("10.9", radix); // 10 // Negative parseInt("-10.1", radix); // -10 parseInt("-10.5", radix); // -10 parseInt("-10.9", radix); // -10

Important note: radix is often omitted by the developers, which means that we let the parseInt function guess the type of number based on the passed argument.

If radix is 0, undefined or not specified, JavaScript assumes:

  • If the input string starts with «0x» or «0X», radix is assumed to be 16.
  • If the input string starts with «0», radix is assumed to be 8 or 10. Exactly which radix is chosen depends on the implementation. ECMAScript 5 clarifies that 10 should be used, but not all browsers support this yet. For this reason, radix must always be specified.
  • If the input string starts with any other value, radix is assumed to be 10.
Читайте также:  Выпадающее меню только html

Bitwise OR (|)

Returns 1 in each bit position for which the corresponding bits of one or both operands are 1s.

The behavior of this operator changes depending on whether you work with positive or negative numbers.

If a number is positive, it is rounded down.

If a number is negative, it is rounded up.

Furthermore, this operator removes everything after the floating-point.

// Positive console.log(10.1 | 0); // 10 console.log(10.5 | 0); // 10 console.log(10.9 | 0); // 10 // Negative console.log(-10.1 | 0); // -10 console.log(-10.5 | 0); // -10 console.log(-10.9 | 0); // -10

Bitwise XOR (^)

Returns 1 in each bit position for which the corresponding bits of one, but not both operands are 1s.

The behavior of this operator is the same as that of Bitwise OR in terms of converting a floating point number into an integer:

// Positive console.log(10.1 ^ 0); // 10 console.log(10.5 ^ 0); // 10 console.log(10.9 ^ 0); // 10 // Negative console.log(-10.1 ^ 0); // -10 console.log(-10.5 ^ 0); // -10 console.log(-10.9 ^ 0); // -10

Double bitwise NOT (~~)

The bitwise NOT operator ( ~ ) takes its operand, converts it to a 32-bit integer and inverts each bit.

Thus 0 becomes 1 and vice-versa.

To simplify things a bit, it yields to -(x+1) :

console.log(~10); // -(10 + 1) = 11 console.log(~-10); // -(-10 + 1) = 9

The double bitwise NOT is itself not an operator, but a combination of two bitwise NOT operators working together.

It yields to -(-(x+1)+1) , which can be simplified to x , so that we end up with our original number.

But there is one important thing to remember: it truncates everything after the floating-point:

// Positive console.log(~~10.1); // 10 console.log(~~10.5); // 10 console.log(~~10.9); // 10 // Negative console.log(~~-10.1); // -10 console.log(~~-10.5); // -10 console.log(~~-10.9); // -10

Subtract The Fractional Part

To do this, we need to use the remainder operator % , which returns the remainder left when an operand is divided by a second operand:

const x = 10.5; const y = -10.5; console.log(x - x % 1); // 10 console.log(y - y % 1); // -10

Summary

As we have seen, there are many ways to convert a floating point number into an integer.

The most commonly used methods are the Math object and the parseInt function, but still it is important to know all available options if you want to use any of them.

What is your favorite way? Let me know in the comments.

Источник

How to Convert a Float to an Int in JavaScript: Top Techniques Explained

Learn the best methods to convert a float to an int in JavaScript, including Math.floor, Math.trunc, parseInt, toFixed, and more. Explore now!

  • Using Math.floor or Math.round
  • Using parseInt()
  • Using parseFloat()
  • Using the Math module
  • Using the trunc() method
  • Using the toFixed() method
  • Using the double bitwise not (~~) operator
  • Using a custom function
  • Other helpful code examples for converting a float to an int in JavaScript
  • Conclusion
  • How to change float to integer in js?
  • Can you convert a float to an int?
  • How to convert to an integer in JavaScript?
  • How to convert decimal into integer in js?
Читайте также:  Php str replace with array

JavaScript is a popular programming language used for both client-side and server-side development. There are various methods to convert a float number to a whole number in JavaScript, such as Math.floor, Math.trunc, parseInt, toFixed, and double bitwise not (~~) operator. In this blog post, we will explore different methods and techniques to convert a float to an int in JavaScript.

Using Math.floor or Math.round

Using Math.floor or Math.round is the fastest and simplest method to cast a float to an int. The Math.floor() function returns the first integer less than or equal to the float. The Math.round() function rounds the float to the nearest integer, and if the float is exactly halfway between two integers, it rounds to the nearest even integer.

let num = 3.14; let floorNum = Math.floor(num); let roundNum = Math.round(num);console.log(floorNum); // Output: 3 console.log(roundNum); // Output: 3 

Using parseInt()

The parseInt() function is widely used in JavaScript to convert a string to an integer. It takes two arguments: the string to convert and the radix, which specifies the base of the number system. If the radix is not specified, it defaults to 10. It returns NaN (Not a Number) if the string cannot be converted to a number.

let numString = "3.14"; let intNum = parseInt(numString);console.log(intNum); // Output: 3 

Using parseFloat()

The parseFloat() function accepts a string as its only argument and returns a float. It is used to convert a string representation of a float to a number. If the string cannot be converted to a number, it returns NaN.

let numString = "3.14"; let floatNum = parseFloat(numString);console.log(floatNum); // Output: 3.14 

Using the Math module

The math module needs to be imported to use the floor() and ceil() functions to convert a float to an int. The floor() function returns the first integer less than or equal to the float. The ceil() function returns the smallest integer greater than or equal to the float.

let num = 3.14; let floorNum = Math.floor(num); let ceilNum = Math.ceil(num);console.log(floorNum); // Output: 3 console.log(ceilNum); // Output: 4 

Using the trunc() method

The trunc() method can be used to get the integer part of a number by removing any fractional digits. It was added in ECMAScript 6 and is supported by most modern browsers. It returns the integer part of the number without rounding the number.

let num = 3.14; let truncNum = Math.trunc(num);console.log(truncNum); // Output: 3 

Using the toFixed() method

The toFixed() method can be used to convert a float to an int by rounding off the number. It takes an argument that specifies the number of decimal places to round the number to. It returns a string representation of the number with the specified number of decimal places.

let num = 3.14; let fixedNum = num.toFixed(0);console.log(fixedNum); // Output: 3 

Using the double bitwise not (~~) operator

The double bitwise not (~~) operator can be used to do a negative-safe truncate. It is a fast and efficient way to truncate a float to an int. It first converts the float to a 32-bit integer and then back to a float.

let num = 3.14; let bitwiseNum = ~~num;console.log(bitwiseNum); // Output: 3 

Using a custom function

The user can also convert an integer to a float in JavaScript using a custom function. This provides more flexibility in converting an integer to a float. The function can take multiple arguments and perform various calculations to convert the integer to a float.

function convertToInt(num)  return parseInt(num); >let num = 3.14; let intNum = convertToInt(num);console.log(intNum); // Output: 3 

Other helpful code examples for converting a float to an int in JavaScript

In javascript, javascript convert float to int code example

function float2int (value) < return value | 0; >float2int(3.75); //3 - always just truncates decimals//other options Math.floor( 3.75 );//3 - goes to floor , note (-3.75 = -4) Math.ceil( 3.75 ); //4 - goes to ceiling, note (-3.75 = -3) Math.round( 3.75 );//4 

In javascript, javascript float to int code example

// x = Number.MAX_SAFE_INTEGER/10 * -1 // -900719925474099.1// value = x // x=-900719925474099 x=-900719925474099.5 x=-900719925474099.6Math.floor(value) // -900719925474099 -900719925474100 -900719925474100 Math.ceil(value) // -900719925474099 -900719925474099 -900719925474099 Math.round(value) // -900719925474099 -900719925474099 -900719925474100 Math.trunc(value) // -900719925474099 -900719925474099 -900719925474099 parseInt(value) // -900719925474099 -900719925474099 -900719925474099 value | 0 // -858993459 -858993459 -858993459 ~~value // -858993459 -858993459 -858993459 value >> 0 // -858993459 -858993459 -858993459 value >>> 0 // 3435973837 3435973837 3435973837 value - value % 1 // -900719925474099 -900719925474099 -900719925474099 

In javascript, syntax — How do I convert a float number to a whole number in JavaScript? code example

### please check the source for in detail explanation ### var intvalue = Math.floor( floatvalue ); var intvalue = Math.ceil( floatvalue ); var intvalue = Math.round( floatvalue );// `Math.trunc` was added in ECMAScript 6 var intvalue = Math.trunc( floatvalue );

In javascript, javascript quick float to integer code example

console.log(23.9 | 0); // Result: 23 console.log(-23.9 | 0); // Result: -23 

Conclusion

In conclusion, there are various methods and techniques to convert a float to an int in JavaScript. Each method has its advantages and disadvantages depending on the specific use case. It is important to choose the appropriate method to convert a float to an int based on the requirements of the application. By understanding these methods and techniques, developers can effectively convert a float to an int in JavaScript.

Источник

Оцените статью