Categories
JavaScript Answers

How to Round Floating-Point Numbers in JavaScript?

Oftentimes, we’ve to round floating-point numbers in our JavaScript web apps.

In this article, we’ll look at how to round floating-point numbers in JavaScript.

Number.prototype.toFixed

JavaScript numbers have the toFixed method that returns a string version of the number rounded to the number of decimal places we passed in as the argument.

For instance, we can write:

const rounded = Number((6.6756854).toFixed(1));  
console.log(rounded)

Then rounded is '6.7' since we passed in 1 to toFixed .

This makes it returns a string rounded to 1 decimal place.

Math.round

Another way to round floating-point numbers is to use the Math.round method.

Math.round returns the rounded number instead of a string.

So we can use it if we want to round a number and keep the returned result as a number.

For instance, we can write:

const number = 6.6756854  
const rounded = Math.round(number * 10) / 10;  
console.log(rounded)

If we want to round to 1 decimal place, then we multiply the number by 10.

Then we call Math.round on that number.

Then we divide by 10 to get the rounded number.

So rounded is '6.7' .

If we want to round to 2 decimal places, then we replace 10 with 100.

And if we round to 3 decimal places, we replace 10 with 1000, and so on.

Number.prototype.toPrecision

We can also use the number’s toPrecision method to return a number that’s rounded to the given decimal place.

It also returns a number instead of a string.

For instance, we can write:

const rounded = (6.6756854).toPrecision(2)  
console.log(rounded)

The argument is the number of decimal places to round to.

So passing in 2 as the first argument would round the number we call it into 2 decimal places.

Therefore, rounded is 6.7.

Math.floor

We can use the Math.floor method to round a number down to the nearest integer.

For instance, we can write:

const rounded = Math.floor(6.6756854)  
console.log(rounded)

Then rounded is 6.

Math.ceil

The Math.ceil method lets us round a number up to the nearest integer.

For instance, we can write:

const rounded = Math.ceil(6.6756854)  
console.log(rounded)

And rounded is 7.

Conclusion

There’re various Math static methods and number instance methods that we can use to round floating-point numbers the way we like.

Categories
JavaScript Answers

How to Detect the Pressing of the Enter key in a Text Input Field with JavaScript?

Sometimes, we want to detect the pressing of the enter key in our code and then do something when that happens.

In this article, we’ll look at how to detect the pressing of the enter key in a text input field with JavaScript.

Check the event.key Property

One way to check which key is pressed is to use the event.key property.

For instance, we can write the following HTML:

<input />

And the following JavaScript code to detect whether the Enter key is pressed:

const input = document.querySelector("input");
input.addEventListener("keyup", (event) => {
  if (event.key === "Enter") {
    console.log('Enter key pressed')
  }
});

We get the input element with the document.querySelector method.

Then we call addEventListener to add an event listener for the keyup event.

Then in the event handler, we check if the event.key property returns 'Enter' .

If it does, then the enter key is pressed.

Check the event.keyCode Property

Another property we can check is the event.keyCode property.

The keyCode property returns a number for the key that’s pressed instead of a string with the key name.

When it returns 13, then we know the enter key is pressed.

So we can write:

const input = document.querySelector("input");
input.addEventListener("keyup", (event) => {
  if (event.keyCode === 13) {
    console.log('Enter key pressed')
  }
});

to check if the key with key code 13 is pressed.

If it is, then we know the enter key is pressed.

Check the event.which Property

Like the event.keyCode property, the event.which property also returns the key code of the key that’s pressed.

For instance, we can write:

const input = document.querySelector("input");
input.addEventListener("keyup", (event) => {
  if (event.which === 13) {
    console.log('Enter key pressed')
  }
});

to do the same check with event.which .

And everything else should be the same as checking with the event.keyCode property.

Conclusion

There’re several properties that comes with input event objects that we can check to see which key is pressed to check whether the enter key is pressed.

Categories
JavaScript Answers

How to Get Image Data as a Base64 URL in JavaScript?

Sometimes, we may want to get our image data as a base64 URL in our web app.

In this article, we’ll look at how to get image data as a base64 URL in JavaScript.

Putting an Image into a Context and Convert the Canvas Data to Base64

One way to convert an image file into a base64 string is to put it into a canvas.

Then we can call the canvas’s toDataURL method to convert it into a base64 string.

For instance, we can write:

const getBase64Image = (url) => {
  const img = new Image();
  img.setAttribute('crossOrigin', 'anonymous');
  img.onload = () => {
    const canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    const ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);
    const dataURL = canvas.toDataURL("image/png");
    console.log(dataURL)
  }
  img.src = url
}

getBase64Image('https://uploads.sitepoint.com/wp-content/uploads/2015/12/1450377118cors3.png')

We create the getBase64Image function that takes the url string for the URL of the image.

Then we create an img eklement with the Image constructor.

Next, we call seAttribute to set the crossOrigin attribute to anonymous so that we can get images that have domains different from what we have.

Next, we create the img.onload method that creates a canvas elemnt with document.createElement .

Then we set the canvas width and height to the img element’s width and height.

Next, we get the canvas context with getContext .

Then we call drawImage to draw the image on the canvas.

The 2nd and 3rd arguments are the x and y coordinates of the top left corner.

Then we call toDataURL with the MIME type that we want to image to have to convert it to a base64 string version of the image.

Then the console.log should log the base64 URL.

Then we set img.src to the url to trigger the onload method to run.

Therefore, when we run getBase64Image with an image URL, we’ll see the base64 string version of it logged.

Conclusion

We can convert an image to a base64 URL by loading the image with the given URL into the canvas and then call toDataURL to convert it to base64.

Categories
JavaScript Answers

How to Select All Contents of a Textbox When it Receives Focus?

Sometimes, we may want to select all the contents of a textbox when it receives focus.

In this article, we’ll look at how to select all the contents of a textbox when it receives focus.

Select All Contents of a Textbox When it Receives Focus

We can select all the contents of a textbox when it receives focus by listening to the focus event.

For instance, we can write the following HTML:

<input type="text" value="test" />

And the following JavaScript code:

const input = document.querySelector('input')
input.addEventListener('focus', () => {
  input.select();
})

input.addEventListener('mouseup', (e) => {
  e.preventDefault()
})

We get the input with querySelector .

Then we call addEventListener with 'focus' as the first argument to listen to the focus event.

Then we call the input’s select method to select all the text inside the input when we click on it to focus on the textbox.

Also, we add a mouseup event listener and call e.preventDefault to stop its default action, which is to deselect on click.

Select Input Text in a Text Input with React

We can do the same thing with React easily.

For instance, we can write:

import React from "react";

export default function App() {
  return (
    <div>
      <input type="text" value="test" onFocus={(e) => e.target.select()} />
    </div>
  );
}

We just pass in a function that calls e.target.select to select all the text in the input as the value of the onFocus prop.

e.target is the input element so we can call select on it to select all the text.

Conclusion

We can select all the text in an input box when we focus on it by writing a few lines of JavaScript code.

Categories
JavaScript Answers

How to Convert Size in Bytes to KB, MB, GB in JavaScript?

Sometimes, we get a number in bytes, and we want to convert it to KB, MB, or GB.

We can do that easily with JavaScript.

In this article, we’ll look at how to convert a byte number to KB, MB, or GB with JavaScript.

Convert Size in Bytes to KB, MB, GB in JavaScript

We can convert a number in bytes to KB, MB, and GB easily with our own JavaScript function.

To create our own function, we write:

const formatBytes = (bytes, decimals = 2) => {
  if (bytes === 0) {
    return '0 Bytes';
  }
  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

console.log(formatBytes(1024))
console.log(formatBytes(1024 * 1024))

We create the formatBytes function that takes the number of bytes and the number of decimals to round the number to.

First we check if bytes is 0.

If it is, we return '0 bytes' .

Next, we create the k constant to set the number of bytes in a kilobyte.

This lets us convert the number of bytes to what we want easily.

dm is the number of decimal places to round to.

We have the sizes array with the units to append to the converted number.

i is the exponent with base kthat’s raised to convert to the number of bytes when we have the number of KB, MB, GB, etc.

This is also the same as the index we use to pick the right unit from the sizes .

Finally, we convert the number of bytes to the unit we want by diving the number of byts by k raised to the power of i .

The number is rounded to the number of decimal places we want with toFixed .

toFixed returns a string with the rounded number in it.

And then we concatenate the string with sizes[1] .

Therefore, the first console log logs '1 KB' .

And the 2nd console log logs '1 MB' .

Conclusion

We can convert the number of bytes to the unit we want easily with math methods that are built into the JavaScript standard library.