52

My API is sending React integers like 10, 31312, 4000.

In my React component, what's the right way to format these numbers like so:

from: 10, 31312, 4000
to: 10, 31,312, 4,000

Update

The number is being provided by my Rails API and rendered in a React component:

const RankingsList = ({rankings, currentUserId}) => {
  return (
      <div className="listGroup">
        {rankings.map((ranking, index) =>
            <span className="number">{ranking.points}</span>
        )}
      </div>
  );
};
halfer
  • 19,824
  • 17
  • 99
  • 186
AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012
  • 2
    Are you getting them as JSON? Can you elaborate a little bit why, and how you will be using them ? – DrunkDevKek Jun 27 '17 at 15:54
  • sorry about that, just updated w an example – AnApprentice Jun 27 '17 at 15:58
  • 2
    Possible duplicate of [How to print a number with commas as thousands separators in JavaScript](https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript) – Jordan Running Jun 27 '17 at 15:59

7 Answers7

94

Print a number with commas as thousands separators in JavaScript

You can find a general JS solution for this:


toLocaleString:

// A more complex example: 
number.toLocaleString(); // "1,234,567,890"

// A more complex example: 
var number2 = 1234.56789; // floating point example
number2.toLocaleString(undefined, {maximumFractionDigits:2}) // "1,234.57"

NumberFormat (Safari not supported):

var nf = new Intl.NumberFormat();
nf.format(number); // "1,234,567,890"

source: https://stackoverflow.com/a/32154217/6200607


var number = 1234567890; // Example number to be converted

⚠ Mind that javascript has a maximum integer value of 9007199254740991


Other Solution:

https://css-tricks.com/snippets/javascript/comma-values-in-numbers/

2345643.00 will return 2,345,643.00

Hassan Ketabi
  • 2,924
  • 2
  • 22
  • 31
43

I have a class which converts a number to either 31,312 or 31,312.00.

The code is pretty much;

return value.toLocaleString(navigator.language, { minimumFractionDigits: 2 });

and

return value.toLocaleString(navigator.language, { minimumFractionDigits: 0 });

So you can just use toLocaleString for converting.

Update

Based on your example, it would be (assuming points is a number);

const RankingsList = ({rankings, currentUserId}) => {
  return (
      <div className="listGroup">
        {rankings.map((ranking, index) =>
            <span className="number">{ranking.points.toLocaleString(navigator.language, { minimumFractionDigits: 0 })}</span>
        )}
      </div>
  );
};

However, you might want to just move this into a smaller component called NumberDisplay and a property to show/hide decimal points'

Tim B James
  • 20,084
  • 4
  • 73
  • 103
  • Thanks Tim, in your React app, are you storing this func in some type of global helper file? – AnApprentice Jun 27 '17 at 16:04
  • @AnApprentice We have a component named NumericDisplay, which takes in a property for NumericFormat that is either NoneFractional or Standard. In this, we then use a NumericHelper file that will return the value. So we use the component in the majority of places, but can also use the helper if we want. – Tim B James Jul 17 '17 at 09:53
5
  export const formatNumber = inputNumber => {
    let formetedNumber=(Number(inputNumber)).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
    let splitArray=formetedNumber.split('.');
    if(splitArray.length>1){
      formetedNumber=splitArray[0];
    }
    return(formetedNumber);
  };

Please note that I am ignoring the decimal points

Vikram Kodag
  • 485
  • 5
  • 6
3
const numberWithCommas = (x) => {
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};
Jazib Khan
  • 31
  • 4
  • How does this work, and what is the improvement over Vikram Kodag's `replace(/\d(?=(\d{3})+\.)/g, '$&,')`? – greybeard Sep 20 '22 at 07:21
  • The regular expression uses a look-ahead to find positions within the string where the only thing to the right of it is one or more groupings of three numbers – Jazib Khan Sep 21 '22 at 08:13
  • and i answered on prespective of integers only Vikram is handling the decimals aswell because the regex i provided will return value for example if i enter the value of x=1233.3332 the output will be : 1,233.3,332 for handling decimals i have found another regex https://stackoverflow.com/questions/2254185/regular-expression-for-formatting-numbers-in-javascript in there look for the answer of @Adam Legget – Jazib Khan Sep 21 '22 at 08:19
  • Don't comment comments asking for explanation (of something not obvious from the post) or additional information: Edit [the post](https://stackoverflow.com/help/how-to-answer). – greybeard Sep 21 '22 at 09:10
  • this works perfectly for react native – Anthony phillips Jan 07 '23 at 04:34
2

React component to format numbers in an input or as text: react-number-format

paprika
  • 617
  • 6
  • 12
0
    import React from 'react'

export default function Test() {

    const [finalAmount, setfinalAmount]= useState("");

    const handleNumChange = (event) => {
    const str = (event.target.value).replace(/\,/g,'');
    setfinalAmount(str);
  }
  return (
    <div>
        <input
                    type="text"
                    onChange={handleNumChange}
                    value={new Intl.NumberFormat('en-IN', {
                    }).format(finalAmount)}
                  />
    </div>
  )
}
Dipanshu
  • 11
  • 4
-1

use this component.

// number cell
function NumberCell({ line, handleBlur, property, readOnly }) {
    function replaceNonNumeric(numStr) {
        return String(numStr).replace(/[^0-9]/g, '')
    }
    function commarize(numStr) {
        return Number(replaceNonNumeric(numStr)).toLocaleString()
    }

   
    useEffect(() => {
        setValue(commarize(line[property.name]))
    }, [line])


    const [value, setValue] = useState(line[property.name])

    const handleChange = e => {
        setValue(commarize(e.target.value))
    }

    function proxyHandleBlur(e) {
        e.target.value = replaceNonNumeric(e.target.value)
        return handleBlur(e)
    }

    return (
        <input 
            name={property.name}
            value={ value }
            onChange={handleChange}
            onBlur={proxyHandleBlur}
            type="text"
            readOnly={readOnly}
            />
    );
}
thumbtackthief
  • 6,093
  • 10
  • 41
  • 87
Gilbert
  • 2,699
  • 28
  • 29