Is there a way to add separative commas to large input numbers? let's say the input was 1000, I want the output for this function to be a casted string that has this format "1,000".

Note: I'm using the Openzepplin unit to string library.

import "@openzeppelin/contracts/utils/Strings.sol";

function myNum(uint256 _Num) public pure returns(string memory){
        return (Strings.toString(_Num));
  • You could parse the number and build your own string, adding a , every x / 1000. But isn't this something you'd want to do on the frontend with a library such as numeraljs?
    – razgraf
    Jan 15 at 16:34
  • The problem is I want this to function inside the smart contract, which means everything has to be on chain. The output will be displayed as an svg.
    – Pequod
    Jan 16 at 9:39

I suggest you do this at client level with a library such as numeraljs. Even so, here's a way to do it directly in solidity. Note: there are probably more efficient or cleaner approaches.

// SPDX-License-Identifier: GPL-3.0

import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol";

pragma solidity 0.8.11;

contract CommaFormatter {

    using Strings for uint256;
    function concat (string memory base, uint256 part, bool isSet) internal pure returns (string memory) {  
            string memory stringified = part.toString();
            string memory glue = ",";

            if(!isSet) glue = "";
            return string(abi.encodePacked(

    function format (uint256 source) public pure returns (string memory) {   
        string memory result = "";
        uint128 index;

        while(source > 0) {
            uint256 part = source % 10; // get each digit
            bool isSet = index != 0 && index % 3 == 0; // if we're passed another set of 3 digits, request set glue

            result = concat(result, part, isSet);
            source = source / 10;
            index += 1;
        return result;


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.