Format String to truncate a number to a specific number of digits

616 Views Asked by At

Is there a format string to truncate a number to a specific number of digits? For example, any number greater than 5 digits i would like to truncate to 3 digits.

132456 -> 132
5000000 -> 500

@Erik : Format specifiers like %2d are specific to a language? I actually want to use it in javascript

2

There are 2 best solutions below

0
On

I assume you refer to printf format strings. I couldn't find anything that will truncate an integer argument (i.e. %d). But you can specify the maximum length of a string by referring to a string format string and specifying lengths via "%<MinLength>.<MaxLength>s". So in your case you could turn your number arguments into strings and then use "%3.3s".

2
On

Pseudo-Code

Function returning a String, receiving a String representing a Number as a parameter
    IF the String has more than 5 characters
        RETURN a substring containing the first 3 characters.
    ELSE
        RETURN the string received as a parameter
    END IF
END Function