DEV Community

Cover image for Displaying numbers as k,M values in Reactjs
MC Naveen
MC Naveen

Posted on

Displaying numbers as k,M values in Reactjs

SI Prefixs are everywhere. Facebook Likes, Twitter Reweets YouTube Views etc. See the example below to understand what I mean.

Example:

Before After
1000 Views 1k Views
25000 Likes 25K Likes
30000 Retweets 30k Retweets

In this post we will see how we can convert the numbers to shortern numbers.

🎉 Make sure to bookmark this for later

We are going to use React for this example, But this works on all nodejs projects

Create a react app

npx create-react-app numbers
Enter fullscreen mode Exit fullscreen mode

Wait until the project gets created.

cd into the directory

cd numbers
Enter fullscreen mode Exit fullscreen mode

Install the required dependency

yarn add numify

or

npm install numify --save
Enter fullscreen mode Exit fullscreen mode

Now in the App.js file paste the below code.

import "./styles.css";
import { numify } from "numify";
import { useState, useEffect } from "react";

export default function App() {
  const [number, setNumber] = useState(null);

  useEffect(() => {
    // Change the Number as per your choice
    setNumber(numify(2700000000));
  }, []);

  return (
    <div className="App">
      <h1>2700000000 will be rendered as {number}</h1>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Then, Run the Project using the command

npm run start
Enter fullscreen mode Exit fullscreen mode

Once the project is started, You'll see this in browser.

Output

I hope you find this useful, Please drop a heart and leave your comments.

🎉 Make sure to bookmark this for later

Top comments (0)