Listado de la etiqueta: Convert

A Date variable can easily be constructed by following two different ways. Both ways essentially include making a call to the new Date() constructor provided by the JavaScript Date Object. This article will look at how to convert a date string into a date variable.

Acceptable Notations of a Date String

Before constructing date variables from Date strings, we must know the acceptable formats of Date strings in JavaScript, which help the user run their code without encountering any errors.

Well, the best notations for the Date strings are the ones set up by the ISO, which is an abbreviation for International Organization for Standardization. Date ISO format and the JavaScript Date object function are the most pleasing string formats for string parsing.

ISO format examples include YYYY-MM-DD and YYYY-MM-DDTHH:MM:SS.

Method 1: Passing an ISO Date String directly Into the Date Constructor

To demonstrate this method, simply create a new date String with the following line:

dateString = «2005 FEB 25»;

After that, simply create a new variable and then set that variable equal to the Date constructor by using the keyword “new”, and in the constructor pass in the dateString as:

date1 = new Date(string);

Then simply pass this date1 variable to the console log function to display it on the terminal and also to verify that this is now a date variable constructed from a string:

Execute the code and observe the following output on the terminal:

It is clear from the result in the terminal that date1 is actually a date variable constructed from a string.

To demonstrate the use of an invalid date string, set the variable dateString equal to an invalid format like:

dateString = «2005 FEB 25th»;

Afterwards, do the same steps, pass this in the Date() constructor and show the result on the terminal using the console log function:

date1 = new Date(dateString);

Upon execution of this, the terminal shows the following outcome:

The result is as “Invalid Date”, which means that not every string can be interpreted into a date variable. That is why following the format for the date string is essential.

Method 2: Use the Date parse() Method to Parse the String First

In this second method, simply start by creating a new date string with the following line:

dateString2 = «1997 Jun 05»;

Now, simply pass this string inside the Date parse() to get the time elapsed from 1st January 1970, till the date represented in the string in the form of milliseconds:

milli = Date.parse(dateString2);

Afterwards, we can use these milliseconds to construct a new Date variable by passing them in the Date constructor like:

Afterwards, simply display the value of the date2 variable on the terminal by using the console log function:

Execute the program, and the terminal will display the following outcome:

It is clear from the output that this is a date variable constructed from the given string. However, if you notice the value on the output that the Date of the month part is one less than the value we passed in the String. It should be the 5th of June, but rather it is the 4th of June in the output.

The reason is that in the Date object or date variables, the “date of the month” part starts from 0 instead of 1. Therefore, the 5th of June 1997 is represented by “1997-06-04”.


We can easily convert a string into a date in JavaScript by using the new Date() constructor, which comes as a default object in JavaScript. The only thing to notice is that not every string can be converted into a date. A proper format setup by ISO must be followed for the date string. The two methods include making a direct call to the new Date() constructor, and the other includes first converting or parsing the string into milliseconds and then making the call to the new Date() constructor.

Source link

In Java, “double” and “int” are the most popular primitive data types, where double is a 64-bit floating-point number and integer, also known as “int”, is a 32-bit integer representing signed two’s complement. While programming in Java, you may need to convert double to int where the input given by the user is in floating points, and an integer value is required for further processing.

This post will teach the procedure of converting double to int in Java.

How to Convert double to int in Java?

Converting a number from double to int is considered a common conversion task in programming. As mentioned earlier, the double data type has a parte value. When these numbers are converted to integers, the parte digits are rounded to the closest number.

In Java, you can convert data type double to int:

    • Using “TypeCasting
    • Using “Double.intValue()” method
    • Using “Math.round()” method

Let’s discuss each of them one by one!

Method 1: Convert double to int in Java by Using TypeCasting

Typecasting is a process of converting one data type to another. It is primarily utilized by Java developers to test the data variable. You can also use it for converting double data type variables to int.


The syntax for converting double to int in Java using TypeCasting method is given as:

d” is the variable that stores a value of data type “double”. The keyword “int” with the parenthesis like “(int)” indicates that the mentioned double type “d” variable is typecasted into an integer, and the resultant value will be stored in “i”.


First, we will create a double type variable “d” and assign it the following value:

Next, we will convert “d” into an int by using typecasting:

After performing the specified operation, we will print the converted value:

System.out.println(«The value in data type Double « + d + » is converted in Integer « + i);


The output shows the integer value “856” after truncating the parte points:

Method 2: Convert double to int in Java by Using Double.intValue() Method

Double.intValue() is another method used to convert the number from double data type to int. The “intValue()” is the method of the Java “Double” Wrapper class. This method converts the double value into the nearest integer value and returns an integer. It works similar to typecasting.


The syntax for converting a number in data type double to int by using “Double.intValue()” method is as follows:

int i = new Double(d).intValue();

Have a look at the following example to know more about the given method.


We will convert the value of the already created “d” variable using the “Double.intValue()” method:

int i = new Double(d).intValue();

The above-given code will create an object of the “Double” Wrapper class and pass a value of “d” in it, and then call the “intValue()” method.

After converting, print the resultant integer value on the console using the “System.out.println()” method:

System.out.println(«The value in data type Double « + d + » is converted in Integer « + i);



Method 3: Convert double to int in Java by Using Math.round() Method

Another method to convert the double to int in Java is the “Math.round()”. It belongs to the Java “Math” class. It takes a double value and rounds it into the nearest integer value.


The syntax for the “Math.round()” method is:

int i = (int)Math.round(d);


We will utilize the same “d” variable and convert its value to “int” using the Math.round() method:

int i = (int)Math.round(d);

At the end, print the integer value on the console:

System.out.println(«The value in data type Double « + d + » is converted in Integer « + i);


You can see the output, which shows the double value “850.171” is rounded off to “850”:

We provided all the necessary instructions related to converting double to int in Java.


To convert double to int in Java, there are three different methods: Typecasting, Math.round(), and Double.intValue(). Typecasting and Double.intValue() methods approximately work the same when utilized for double to int conversion. Typecasting is performed explicitly. In contrast, the Math.round() method rounds off the double value to an integer value. In this post, we have discussed the procedure for converting double to int in Java with examples.

Source link

Often, you may need to convert or add the images to the PDF files, especially if you have an application and you want the users to download the images as PDF files.

There are different online tools that convert the images to PDF. But security is always a concern, and you can’t trust these online sites with your data. The best method is to convert the images on your machine. Linux offers various command-line utilities to aid you with that. The two common tools are Img2PDF and ImageMagick.

1. ImageMagick

ImageMagick stands out for the image conversion to PDF for its fast speed. The open-source Linux tool utilizes the multiple CPU threads to keep the conversion process fast. Whether converting one image or multiple images, ImageMagick gets the job done.

Let’s first install ImageMagick using the following command:


$ sudo apt update

$ sudo apt install -y imagemagick

For Fedora users, the command is as follows:


$ sudo dnf install imagemagick

With the ImageMagick already installed, navigate to the directory containing your pictures. We have different images in our example. We will see how we can convert them one by one and how to convert them all at merienda.

The syntax for conversion is as following:


$ convert image demo.pdf

Note that we are using convert, a utility for ImageMagick. Let’s start by converting one image.

If you run the previous convert command, it should work fine. However, you may end up with an error message like the one reflected in the following image:

In that case, all you need is to edit the policy.xml file using an editor like nano.


$ sudo nano /etc/ImageMagick-6/policy.xml

Look for the line in the following example:


<policy domain=«coder» rights=«none» pattern=«PDF» />

To fix the error, replace the rights from “none” to “read|write”

Save the file and rerun the command. You will now have a PDF file of the converted image.

To convert all the images in the current directory to PDF, you can add their names one by one or select the image format if they are the same. In our case, the image formats are in “.jpg”. In this case, our command is as follows:

That’s it! You now have all your images converted into one PDF.

ImageMagick is a great tool for converting the images to PDF on the command line. The only bad side of it is that the resolution for the images changes and the PDF file doesn’t have the full resolution, reducing the image quality.


2. Img2PDF

The ImageMagick converts the images to PDF, but the quality of the images reduces. The alternative is to use the Img2PDF to convert the same photos without losing the image quality. Besides, Img2PDF allows the specification of the image size when converting.

Start by installing Img2PDF using the following command:


$ sudo apt install img2pdf

You can verify the installation by checking the version.

Img2PDF can also be installed using pip in other distributions:

With the tool installed, let’s proceed to convert our images. We use the same pictures as we did with ImageMagick. First, navigate to the directory that contains your images. To convert a single file, use the following syntax:


$ img2pdf img -o converted.pdf

We now have a PDF version of the image. If you want to convert multiple images, you can list them all. Or if they have the same format, use the * shorthand like in the following example:

To specify the page size or the image size for the output, use the –imgsize or –pagesize.

For instance, to specify the image size to 30cm by 45cm, the command is:


$ img2pdf <image> –imgsize 30cmx45cm -o output.pdf


Converting the images of different formats to PDF shouldn’t trouble you when using Linux. There are command-line utilities at your disposal, and the syntax is easy. This guide has presented two utilities, Img2PDF and ImageMagick, that you can use to convert either one or multiple images to PDF.

Source link

Pandas is a free and open-source Python library that provides fast, flexible, and expressive data structures that make working with scientific data easy.

Pandas is one of Python’s most valuable data analysis and manipulation packages.

It offers features such as custom data structures that are built on top of Python.

This article will discuss converting a column from one data type to an int type within a Pandas DataFrame.

Setting Up Pandas

Before diving into how to perform the conversion operation, we need to setup Pandas in our Python environment.

If you are using the almohadilla environment in the Anaconda interpreter, chances are you have Pandas installed.

However, on a native Python install, you will need to install it manually.

You can do that by running the command:

On Linux, run

$ sudo pip3 install pandas

In Anaconda or Miniconda environments, install pandas with conda.

$ conda install pandas
$ sudo conda install pandas

Pandas Create Sample DataFrame

Let us set up a sample DataFrame for illustration purposes in this tutorial. You can copy the code below or use your DataFrame.

import pandas as pd
df = pd.DataFrame({‘id’: [‘1’, ‘2’, ‘3’, ‘4’, ‘5’],
                   ‘name’: [‘Marja Jérôme’, ‘Alexios Shiva’, ‘Mohan Famke’, ‘Lovrenco Ilar’, ‘Steffen Angus’],
                   ‘points’: [‘50000’, ‘70899’, ‘70000’, ‘81000’, ‘110000’]})

Merienda the DataFrame is created, we can check the data.

Pandas Show Column Type

It is good to know if the existing type can be cast to an int before converting a column from one type to an int.

For example, attempting to convert a column containing names cannot be converted to an int.

We can view the type of a DataFrame using the dtypes property

Use the syntax:

In our sample DataFrame, we can get the column types as:

id        object
name      object
points    object
dtype: object

We can see from the output above that none of the columns hold an int type.

Pandas Convert Column From String to Int.

To convert a single column to an int, we use the astype() function and pass the target data type as the parameter.

The function syntax:

DataFrame.astype(dtype, copy=True, errors=‘raise’)

  1. dtype – specifies the Python type or a NumPy dtype to which the object is converted.
  2. copy – allows you to return a copy of the object instead of acting in place.
  3. errors – specifies the action in case of error. By default, the function will raise the errors.

In our sample DataFrame, we can convert the id column to int type using the astype() function as shown in the code below:

df[‘id’] = df[‘id’].astype(int)

The code above specifies the ‘id’ column as the target object. We then pass an int as the type to the astype() function.

We can check the new data type for each column in the DataFrame:

id         int32
name      object
points    object
dtype: object

The id column has been converted to an int while the rest remains unchanged.

Pandas Convert Multiple Columns to Int

The astype() function allows us to convert more than one column and convert them to a specific type.

For example, we can run the following code to convert the id and points columns to int type.

df[[‘id’, ‘points’]] = df[[‘id’, ‘points’]].astype(int)

Here, we are specifying multiple columns using the square bracket notation. This allows us to convert the columns to the data type specified in the astype() function.

If we check the column type, we should see an output:

id         int32
name      object
points     int32
dtype: object

We can now see that the id and points column has been converted to int32 type.

Pandas Convert Multiple Columns to Multiple Types

The astype() function allows us to specify a column and target type as a dictionary.

Assume that we want to convert the id column to int32 and the points column to float64.

We can run the following code:

convert_to = {«id»: int, «points»: float}
df = df.astype(convert_to)

In the code above, we start by defining a dictionary holding the target column as the key and the target type as the value.

We then use the astype() function to convert the columns in the dictionary to the set types.

Checking the column types should return:

id          int32
name       object
points    float64
dtype: object

Note that the id column is int32 and the points column is of float32 type.

Pandas Convert Column to Int – to_numeric()

Pandas also provides us with the to_numeric() function. This function allows us to convert a column to a numeric type.

The function syntax is as shown:

 pandas.to_numeric(arg, errors=‘raise’, downcast=None)

For example, to convert the id column to numeric in our sample DataFrame, we can run:

df[‘id’] = pd.to_numeric(df[‘id’])

The code should take the id column and convert it into an int type.

Pandas Convert DataFrame to Best Possible Data Type

The convert_dtypes() function in Pandas allows us to convert an entire DataFrame to the nearest possible type.

The function syntax is as shown:

DataFrame.convert_dtypes(infer_objects=True, convert_string=True, convert_integer=True, convert_boolean=True, convert_floating=True)

You can check the docs in the resource below:

For example, to convert our sample DataFrame to the nearest possible type, we can run:

If we check the type:

id         Int32
name      string
points     Int64
dtype: object

You will notice that each column has been converted to the nearest appropriate type. For example, the function converts small ints to int32 type.

Likewise, the names column is converted to string type as it holds string values.

Finally, since the points column holds larger integers, it is converted to an int64 type.


In this article, we gave detailed methods and examples of converting a Pandas DataFrame from one type to another.

Source link