Source Freeze

  • Home
  • iOS
  • Swift
  • Cross-Platform
  • About
  • Contact
Home » javascript » Page 4

Parse Float with 2 decimals in javascript

January 12, 2023 by Source Freeze Leave a Comment

In this tutorial, we will more about how to parse the float with 2 decimals in JavaScript.

Parse Float with 2 decimals in javascript

Parse Float with 2 Decimals in JavaScript

To parse float with 2 decimal places:

  1. First, use the toFixed() method to specify the number of decimal places you want to round the number to. This method rounds the number to the nearest decimal place and Also toFixed() will return the result as a string.
  2. toFixed() method rounds the number up or down, depending on the next decimal place. If you want to always round down, you can use the Math.floor() or round up you can use Math.ceil()
  3. Finally, to convert the parsed number back to a number and not a string, use the parseFloat(), this will convert the string to float.

let us see parse float with 2 decimals by example.

First, assign a value that holds the floating point number which we want to parse.

let num = 6.16659265;

Then use toFixed() a method like below also mentions the number of decimal places we want to round the number for example in the below case I have mentioned 2 decimal places.

let parsedNum = num.toFixed(2);

The toFixed() method rounds the number up or down, depending on the next decimal place. If we want to always round down, we can use the Math.floor() function. if you want nearest integer please use Math.round() function see the last example.

let parsedNum = Math.floor(num * 100) / 100;

If we want to always round up, we can use the Math.ceil() function.

let parsedNum = Math.ceil(num * 100) / 100;

Finally, If we need to convert the parsed number to a string, use the parseFloat() else you can you the value from the last step directly, like the below example.

let finalNumber = parseFloat(parsedNum);

Also, we can use the Math.round() function to method returns the value of a number rounded to the nearest integer.

let parsedNum = Math.round(num * 100) / 100;

Thanks, hope this tutorial is helpful Parse Float with 2 decimals in javascript.

Please let us know if any help is needed. Thanks.

☞ Check out The Complete JavaScript Course 2023: From Zero to Expert! (Buy now, the offer ends in a few hours)

Also please check our other javascript tutorials.

☞ How to convert array to space separated strings in javascript

☞ How to convert array to comma separated strings in javascript

Filed Under: javascript Tagged With: javascript

How to redirect to another page in next js

January 8, 2023 by Source Freeze Leave a Comment

In this tutorial, we will see how to redirect to another page in next js, there are three ways to redirect one page to another page in nextjs.

  1. Using Link in Next.js
  2. useRouter() Hook by using router.push
  3. config.next.js
  4. Middleware

Let’s see each option in a detailed way.

How to redirect to another page in next js

Using Link Component in Next.JS

Using Link component in nextjs it is like a href tag you can just use the href attribute and mention the redirect URL, please refer the below example.

☞ Check out Next.js & React – The Complete Guide (incl. Two Paths!) (Buy now, offer ends in a few hours)

First we need import the Link from the next/link module

import Link from 'next/link';

// ...

return (
  <div>
    <Link href="/new-url">
      <a>Click here to redirect</a>
    </Link>
  </div>
);

How to redirect to another page using useRouter() Hook onclick

We can use the useRouter hook from next/router to get access to the router object in your functional component, and then we can use the push method to navigate to another page on the buttonn onclick event.

Let’s see an example using userRouter in the below.

import { useRouter } from 'next/router';

function MyComponent() {
  const router = useRouter();

  const handleClick = () => {
    router.push('/new-page');
  };

  return (
    <button onClick={handleClick}>Go to new page</button>
  );
}

While clicking the Go to new page button, it will navigate to the /new-page page.

We can also use the router.push method to pass query parameters to the new page, as mentioned in the below example.

import { useRouter } from 'next/router';

function MyComponent() {
  const router = useRouter();

  const handleClick = () => {
  router.push({
  pathname: '/new-page',
  query: {
    name: 'Source Freeze',
    count: 30,
  },
  });
  };

  return (
    <button onClick={handleClick}>Go to new page</button>
  );
}

This will navigate to the /new-page page and pass the query parameters name and count to it.

How to redirect to another page using config.next.js

We can redirect a one to another page using config.next.js but this is fixed redirect mostly it is used for ther permanent redirect it is not a logic based, in some cases you need to get the benefit SEO for the redirection or permanent redirection we will use this approach, please refer the below to redirect to another page using config.next.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  async redirects() {
     return [
                {
                    source: '/old-page',
                    destination: '/',
                    permanent: true,
                 },
            ]
    },
}
module.exports = nextConfig

Middleware

Next we can achive the redirection using the Middleware, this middleware redirection we can use the conditional based redirection.

Please refer the beloe example.

import {  NextResponse } from 'next/server'
export function middleware(request) {
if ( request.id === 1 ) {
return NextResponse.rewrite(new URL('/page-1', request.url))
} else if (request.id === 2) {
return NextResponse.redirect(new URL('/page-2', request.url))
} else {
return NextResponse.rewrite(new URL('/not-found', request.url))
}
return NextResponse.next()
}

Here in this tutorial we have seen all the options of redirect to another page in next js.

Thanks for reading also you can refer the below tutorial how to get the query params from the URL in NextJS

☞ Check out Next.js & React – The Complete Guide (incl. Two Paths!) (Buy now, offer ends in a few hours)

Filed Under: javascript, NextJS Tagged With: javascript, nextjs

How to get the query parameters from URL in Next JS?

January 5, 2023 by Source Freeze Leave a Comment

In nextjs we can easily get the query params with the use of useRouter() that we can import from 'next/router' then assign userRouter() to the router variable after that using router.query we can get the exact query string values. if you are passing multiple queries also we can get the values from router.query.

☞ Check out Next.js & React – The Complete Guide (incl. Two Paths!) (Buy now, offer ends in a few hours)

how to get the query params from URL in nextjs

Here in the example, we can see the detailed way, how to get the query params from the URL in NextJS it is applicable for single query params or multiple query params.

First, we can see how to pass the query params to the link to the next calling page, refer to the below code.

import Link from "next/link";

<Link href={{ pathname: '/search', query: { keyword: 'source freeze' } }}>

<a>Search</a>

</Link>

Then next we need to get the query params from the URL, here we are three options to get the query params, please refer to the below options.

  1. In Component
  2. Using getServerSideProps Function
  3. In API Routes

First, we can see the option to get query params in the component

Access Query Params in the Component

To get the query params in the component first we need to import the useRouter from the ‘next/router’, then create a variable router and assign the useRouter to that variable, then using router.query we can able to get the exact params, used anywhere on the page.

import { useRouter } from 'next/router';

function Search(props) {
  const router = useRouter();

  // Get the query parameter from the URL
  const { keyword } = router.query;

  return (
    <div>
      The Search Keyword {keyword}.
    </div>
  );
}

export default Search;

Also if you have passed multiple keywords we can easily access them like the one below.

import { useRouter } from 'next/router';

function Search(props) {
  const router = useRouter();

  // Get the query parameter from the URL
  const { keyword1, keyword2 } = router.query;

  return (
    <div>
      The Search Keyword {keyword1} {keyword2}.
    </div>
  );
}

export default Search;

Next, we can see the option how to get the query params using getServerSideProps function

How to Get Query Parameters In a getServerSideProps

Using getServerSideProps function in Next.js we can generate server-side rendered pages, also it receives a context object as an argument, which contains a query property that holds the query parameters for that page.

We can access the query parameters by accessing the context value below.

export async function getServerSideProps({ context }) {
// context value contains the query params
const param = context.paramName;
}

If we want to access multiple query parameters, we can access them like the one below.

export async function getServerSideProps({ context }) {
const queryparam1 = context.param1;
const queryparam2 = context.param2;
const queryparam3 = context.param3;
}

Accessing Query Params In API Routes

We can also access query params by API route, we will get the req object property by destructuring the request object we can access the query params.

Here’s an example to access the query params in the API routes

import { NextApiRequest, NextApiResponse } from 'next';

export default (req: NextApiRequest, res: NextApiResponse) => {
const { query } = req;
const queryParams = query.paramName;

res.status(200).json({ queryParams });
};

Conclusion:

So there are three methods we can access the query params in NextJS

  1. In the component, we can useRouter() hook to access query parameters.
  2. In a server-side rendered page using getServerSideProps, we can access query parameters by destructuring the query property from the context.
  3. In an API route, we can access query parameters by destructuring the query property from the req object.

☞ Check out Next.js & React – The Complete Guide (incl. Two Paths!) (Buy now, offer ends in a few hours)

Filed Under: javascript, NextJS Tagged With: javascript, nextjs

How to convert array to space separated strings in javascript

August 13, 2022 by Source Freeze Leave a Comment

To convert array to space separated strings in javascript we can use the join() method of an array, by passing the string with space as a parameter. the Array.join() method returned the strings with spaces as an output.

☞ Check out The Complete JavaScript Course 2023: From Zero to Expert! (Buy now, the offer ends in a few hours)

The Array.prototype.join() method, this Array.join() method is used to join() all the array with the specified characters.

Please refer to the below example we have passed the arr=[“javascript”,”typescript”,”react”,”angular”] to the arrValue to join(' ') method of the array, then the join() method will return the values as space separated strings as an output. e.g ‘javascript typescript react angular’

The join() method creates and returns a new string by concatenating all of the elements in an array

// ** convert array to space separated strings **
let arrValue = ['javascript', 'typescript', 'react', 'angular']; const strValue = arrValue.join(' '); console.log(strValue); // 'javascript typescript react angular' console.log(typeof strValue); // string

if we called the array.join(’ ‘) method with an empty array, it will return the string with spaces.

console.log([].join(' ')); // '' 

***************

Related Post(Array to Comma Separated Strings): 

How to convert array to comma separated strings in javascript

*****************

the Array.prototype.join() will take the specified separator as the parameter in our case we have used space as a separator but if want to use a different separator we can use it it will be separated based on the specified separator character for example space, comma separated,  “-”, “#”, or whatever you want.

For more details please find the below example.

const arrValue = ['javascript', 'typescript', 'react'];
const spaceAndComma = arrValue.join(', ');
console.log(spaceAndComma); // 'javascript, typescript, react'

const hash = arrValue.join('#');
console.log(hash); // 'javascript#typescript#react'

const hypens = arrValue.join('-');
console.log(hypens); // 'javascript-typescript-react'

const noSeparator = arrValue.join('');
console.log(noSeparator); // 'javascripttypescriptreact'
convert array to space separated strings

Please let me know if any clarifications to convert array to space separated strings in the comments. Thanks.

☞ Check out The Complete JavaScript Course 2023: From Zero to Expert! (Buy now, the offer ends in a few hours)

Filed Under: javascript Tagged With: javascript

How to convert array to comma separated strings in javascript

August 11, 2022 by Source Freeze Leave a Comment

To Convert array to comma separated strings in Javascript first need to pass the array to the String object like String(arr), then the String(arr) will return the comma separated strings as an output.

☞ Check out The Complete JavaScript Course 2023: From Zero to Expert! (Buy now, the offer ends in a few hours)

Please refer to the below example here we have passed the arrValue=[“javascript”,”typescript”,”react”,”angular”] to the String object, then the String object will return the values as comma separated output like ‘javascript,typescript,react,angular’

The String object is used to represent and manipulate a sequence of characters.

let arrValue = ['javascript', 'typescript', 'react', 'angular'];

 let strValue = String(arrValue);

 console.log(strValue); //  'javascript,typescript,react,angular'

 console.log(typeof strValue); //  string

Alternatively, we can use the Array.prototype.join() method, this Array.join() method is used to join() the all the array with the specified characters.

To convert array to comma separated strings in javascript we can use the join() method of an array, by passing the comma as a parameter. the Array.join() method returned the comma separated strings as an output.

Please refer to the below example we have passed the arrValue=[“javascript”,”typescript”,”react”,”angular”] to the arrValue to join() method of array, then join() method will return the values as comma separated output. e.g ‘javascript,typescript,react,angular’

The join() method creates and returns a new string by concatenating all of the elements in an array

let arrValue = ['javascript', 'typescript', 'react', 'angular'];

 const strValue = arrValue.join(',');

 console.log(strValue); // 'javascript,typescript,react,angular'

 console.log(typeof strValue); //  string

the Array.prototype.join() will take the specified separator as the parameter in our case we have used a comma as a separator but if want to use a different separator we can use it it will be separated based on the specified separator character for example space, #, or whatever you want.

**************

Related Post: Convert Array to Space Separated Strings

*************

Array to comma separated strings in JavaScript

☞ Check out The Complete JavaScript Course 2023: From Zero to Expert! (Buy now, the offer ends in a few hours)

Filed Under: javascript Tagged With: javascript

« Previous Page

Recent Posts

  • How to Generate random numbers in JavaScript
  • How to Scroll to an Element in a React Component?
  • How to get a Date without the Time in JavaScript
  • How to modify url without reloading the page using javascript
  • How to disable server side rendering in nextjs
  • How to get a file type from URL in JavaScript

Recent Posts

  • How to Generate random numbers in JavaScript
  • How to Scroll to an Element in a React Component?
  • How to get a Date without the Time in JavaScript
  • How to modify url without reloading the page using javascript
  • How to disable server side rendering in nextjs
  • How to get a file type from URL in JavaScript

Recent Comments

    Tags

    beginner colon cross-platform es6 function html ionic iOS javascript mobile application development nextjs objective-c swift switch ternary typescript uiwebview Visual Studio plugin web developer

    Copyright © 2025 Source Freeze