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 );

Math object reference


Examples

Positive
// value=x        //  x=5          5<x<5.5      5.5<=x<6  

Math.floor(value) //  5            5            5
Math.ceil(value)  //  5            6            6
Math.round(value) //  5            5            6
Math.trunc(value) //  5            5            5
parseInt(value)   //  5            5            5
~~value           //  5            5            5
value | 0         //  5            5            5
value >> 0        //  5            5            5
value >>> 0       //  5            5            5
value - value % 1 //  5            5            5
Negative
// value=x        // x=-5         -5>x>=-5.5   -5.5>x>-6

Math.floor(value) // -5           -6           -6
Math.ceil(value)  // -5           -5           -5
Math.round(value) // -5           -5           -6
Math.trunc(value) // -5           -5           -5
parseInt(value)   // -5           -5           -5
value | 0         // -5           -5           -5
~~value           // -5           -5           -5
value >> 0        // -5           -5           -5
value >>> 0       // 4294967291   4294967291   4294967291
value - value % 1 // -5           -5           -5
Positive - Larger numbers
// x = Number.MAX_SAFE_INTEGER/10 // =900719925474099.1

// value=x            x=900719925474099    x=900719925474099.4  x=900719925474099.5
           
Math.floor(value) //  900719925474099      900719925474099      900719925474099
Math.ceil(value)  //  900719925474099      900719925474100      900719925474100
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       //  858993459            858993459            858993459
value - value % 1 //  900719925474099      900719925474099      900719925474099
Negative - Larger numbers
// x = Number.MAX_SAFE_INTEGER/10 * -1 // -900719925474099.1

// value = x      // x=-900719925474099   x=-900719925474099.5 x=-900719925474099.6

Math.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
Answer from moonshadow on Stack Overflow
Top answer
1 of 16
2261
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 );

Math object reference


Examples

Positive
// value=x        //  x=5          5<x<5.5      5.5<=x<6  

Math.floor(value) //  5            5            5
Math.ceil(value)  //  5            6            6
Math.round(value) //  5            5            6
Math.trunc(value) //  5            5            5
parseInt(value)   //  5            5            5
~~value           //  5            5            5
value | 0         //  5            5            5
value >> 0        //  5            5            5
value >>> 0       //  5            5            5
value - value % 1 //  5            5            5
Negative
// value=x        // x=-5         -5>x>=-5.5   -5.5>x>-6

Math.floor(value) // -5           -6           -6
Math.ceil(value)  // -5           -5           -5
Math.round(value) // -5           -5           -6
Math.trunc(value) // -5           -5           -5
parseInt(value)   // -5           -5           -5
value | 0         // -5           -5           -5
~~value           // -5           -5           -5
value >> 0        // -5           -5           -5
value >>> 0       // 4294967291   4294967291   4294967291
value - value % 1 // -5           -5           -5
Positive - Larger numbers
// x = Number.MAX_SAFE_INTEGER/10 // =900719925474099.1

// value=x            x=900719925474099    x=900719925474099.4  x=900719925474099.5
           
Math.floor(value) //  900719925474099      900719925474099      900719925474099
Math.ceil(value)  //  900719925474099      900719925474100      900719925474100
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       //  858993459            858993459            858993459
value - value % 1 //  900719925474099      900719925474099      900719925474099
Negative - Larger numbers
// x = Number.MAX_SAFE_INTEGER/10 * -1 // -900719925474099.1

// value = x      // x=-900719925474099   x=-900719925474099.5 x=-900719925474099.6

Math.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
2 of 16
348

Bitwise OR operator

A bitwise or operator can be used to truncate floating point figures and it works for positives as well as negatives:

function float2int (value) {
    return value | 0;
}

Results

float2int(3.1) == 3
float2int(-3.1) == -3
float2int(3.9) == 3
float2int(-3.9) == -3

Performance comparison?

I've created a JSPerf test that compares performance between:

  • Math.floor(val)
  • val | 0 bitwise OR
  • ~~val bitwise NOT
  • parseInt(val)

that only works with positive numbers. In this case you're safe to use bitwise operations well as Math.floor function.

But if you need your code to work with positives as well as negatives, then a bitwise operation is the fastest (OR being the preferred one). This other JSPerf test compares the same where it's pretty obvious that because of the additional sign checking Math is now the slowest of the four.

Note

As stated in comments, BITWISE operators operate on signed 32bit integers, therefore large numbers will be converted, example:

1234567890  | 0 => 1234567890
12345678901 | 0 => -539222987
🌐
Reddit
reddit.com › r/typescript › trying to create a floating point type?
r/typescript on Reddit: Trying to create a floating point type?
November 13, 2023 -

Hey all, the work I'm currently doing involves me receiving all of my values from some machines as a long string, with all of our variables separated by commas. The problem is that a lot of these values have floating numbers that require a set amount of decimal accuracy, so I can have something like 10.0000 that I would like to maintain as a valid number. Is there any way I can create some sort of type that can maintain the floating zeroes as a value like a string, but be treated as a number? I'm just sick of typing all of our variables with names like somethingNumber: string, it's driving me bananas.

Discussions

Convert a Float number to an Int type
I am trying to convert a float number to an integer. The reason is that I want the E8S equivalent of 1 ICP of a value, for example 1.15. This should be 115_000_000, but the function returns 114_000_000. Other values ​​are calculated correctly, for example 1.25 = 125_000_000 or 0.9 = 90_000_000. ... More on forum.dfinity.org
🌐 forum.dfinity.org
0
0
June 10, 2024
performance - Fastest way to cast a float to an int in javascript? - Stack Overflow
The issue with bitwise operators ... to 32bit integers in the process, if that is fine for your use-case then go ahead. See MDN docs on bitwise OR, bitwise NOT, bitwise AND and bitwise XOR or their respective ECMAScript documentation. The parseInt function is usually way slower than the alternatives, most likely because it expects a string as parameter. The solution with the modulo operator should be used with caution as it may bite you in the ass sometime due to floating point issues ... More on stackoverflow.com
🌐 stackoverflow.com
December 4, 2015
How can I convert from float to int without undefined behavior?
Why not do the bounds checking? The behavior you're describing doesn't sound like it will meet the needs of everyone (or every instruction set), so I'd recommend just writing the function that has the instructions and behavior that meets your needs More on reddit.com
🌐 r/Zig
16
12
October 17, 2023
Trying to create a floating point type?
You could represent 10.0000 as an object, such as {int: BigInt(10_0000), shift_10: 4}. This will let you store and report an arbitrary level of precision, though it will be more cumbersome to use than JS’s built-in floating-ish-point number type. More on reddit.com
🌐 r/typescript
23
5
November 13, 2023
🌐
Code Highlights
code-hl.com › home › javascript › tutorials
5 Easy Ways to Convert JavaScript Float to Int | Code Highlights
June 4, 2024 - All these methods are compatible with major web browsers, including Chrome, Firefox, Safari, Edge, and Internet Explorer. This ensures that your code will run smoothly across different environments. In this tutorial, we explored five simple methods to convert a JavaScript float to an int:
🌐
Delft Stack
delftstack.com › home › howto › javascript › javascript float to int
How to Convert a Float Number to Int in JavaScript | Delft Stack
February 2, 2024 - We can apply the bitwise right shift operator (represented by >> characters). It will convert the float value to an integer. Underneath at the binary level, the bitwise right SHIFT operator shifts the binary bits of the operand to the right ...
🌐
TutorialsPoint
tutorialspoint.com › how-do-i-convert-a-float-number-to-a-whole-number-in-javascript
How do I convert a float number to a whole number in JavaScript?
In the above output users can see that Math.trunc() method has removed the decimal part and Math.round() method has rounded the number to nearest integer. In this approach, we will use the parseInt() method. The parseInt() method extracts the whole number from the float number or string in ...
🌐
Webdevtutor
webdevtutor.net › blog › typescript-float-to-int
Converting Float to Int in TypeScript: A Comprehensive Guide
One common way to convert a float to an int in TypeScript is by using the Math.floor() function. This function rounds down a number to the nearest integer.
🌐
Webdevtutor
webdevtutor.net › blog › typescript-parse-float-to-int
How to Parse Float to Int in TypeScript
To convert a float value to an integer in TypeScript, you can use the parseInt() function. This function takes a string as its input and returns an integer after parsing the input.
🌐
Webdevtutor
webdevtutor.net › blog › typescript-cast-float-to-int
TypeScript: How to Cast Float to Int
Converting float numbers to integers in TypeScript is a common requirement in many applications. By using methods like Math.floor() and type assertions, you can easily cast float numbers to ints in TypeScript.
Find elsewhere
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › parseFloat
parseFloat() - JavaScript - MDN - Mozilla
A floating point number parsed from the given string, or NaN when the first non-whitespace character cannot be converted to a number. Note: JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. parseInt() and parseFloat() only differ in their parsing behavior, but not necessarily their return values.
🌐
Byby
byby.dev › js-float-to-int
How to convert float to integer in JavaScript
You can use various methods that either round, truncate, or parse the float value. Depending on your specific use case, you can choose the most appropriate method: Using Math.trunc(). This method returns the integer part of a number by removing any fractional digits.
🌐
Internet Computer Developer Forum
forum.dfinity.org › developers
Convert a Float number to an Int type - Developers - Internet Computer Developer Forum
June 10, 2024 - I am trying to convert a float number to an integer. The reason is that I want the E8S equivalent of 1 ICP of a value, for example 1.15. This should be 115_000_000, but the function returns 114_000_000. Other values ​​are calculated correctly, for example 1.25 = 125_000_000 or 0.9 = 90_000_000. public func convertFloatToNat(x: Float): async Int { let ONE_ICP_IN_E8S = 100_000_000; Debug.print("convertFloatToNat "#debug_show(x)); let a = x * 100; Debug.print("float x 100 = "#...
🌐
Tutorial Teacher
tutorialsteacher.com › typescript › typescript-number
TypeScript Data Type - Number
In the above example, let first:number = 1; stores a positive integer as a number.let second: number = 0x37CF; stores a hexadecimal as a number which is equivalent to 14287. When you print this number on your browser's console, it prints the equivalent floating point of the hexadecimal number.let third:number=0377; stores an octal number equivalent to 255.
🌐
typescriptlang.org
typescriptlang.org › docs › handbook › 2 › everyday-types.html
TypeScript: Documentation - Everyday Types
Each has a corresponding type in TypeScript. As you might expect, these are the same names you’d see if you used the JavaScript typeof operator on a value of those types: string represents string values like "Hello, world" number is for numbers like 42. JavaScript does not have a special runtime value for integers, so there’s no equivalent to int or float ...
🌐
Rip Tutorial
riptutorial.com › float to integer
JavaScript Tutorial => Float to Integer
The floor function returns the first integer less than or equal to the float.
🌐
Atomic Spin
spin.atomicobject.com › 2018 › 11 › 05 › using-an-int-type-in-typescript
Using an Int Type in TypeScript - Atomic Spin
November 5, 2018 - So even though I knew that the end result would always be a whole number, by forgetting about the inaccuracies of floating point numbers, I let a bug slip through. In order to ensure that the result is always an integer, as required by the PostgreSQL database, it needs to be rounded: ... Forgetting to round the result of a calculation, when you know full well the result should be a whole number, is very easy to do. A teammate suggested that we use TypeScript to force us to round the result by coming up with an Int type we could use whenever a value was going to be inserted into an integer column in the database.
🌐
W3docs
w3docs.com › javascript
How to Convert a Float Number to Whole Number in JavaScript
The parseInt() function parses the string argument and returns an integer of the given radix. ... The ~~ operator rounds a number towards 0 if the operand is a number and it’s not NaN or Infinity. ... The OR operator rounds a number towards 0. ... There are two types of numbers in JavaScript: Regular and BigInt. Regular is also known as “double-precision floating-point numbers”. The math is a built-in object which has properties and methods for mathematical constants and functions.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-convert-a-float-number-to-the-whole-number-in-javascript
How to Convert a Float Number to the Whole Number in JavaScript? | GeeksforGeeks
September 16, 2024 - // float value is 4.59; let x = 4.59; let z = Math.floor(x); console.log("Converted value of " + x + " is " + z); ... Return the smallest integer greater than or equal to a given number.
🌐
TypeScript Tutorial
typescripttutorial.net › home › typescript tutorial › typescript number
TypeScript Number
October 18, 2024 - All numbers in TypeScript are either floating-point values or big integers. The floating-point numbers have the type number while the big integers get the type bigint. The following shows how to declare a variable that holds a floating-point value:
🌐
Medium
medium.com › interesting-coding › all-typescript-types-you-need-to-know-dd1423fd6687
All TypeScript Types You Need To Know | by Cihan | Interesting Coding | Medium
November 10, 2023 - In TypeScript, there are several built-in types that can be used to specify the type of a variable, function parameter, or function return value. These include: boolean: Represents a value that is either true or false. number: Represents a numeric value, either integer or floating-point.