AddThousandsSeparators

From SA-MP Wiki

(Difference between revisions)
Jump to: navigation, search
Revision as of 14:57, 2 April 2016
OstGot (Talk | contribs)
(Another update by DeimoS)
← Previous diff
Revision as of 12:14, 4 April 2016
Vince (Talk | contribs)
(AddCommas moved to AddThousandsSeparators: Bad name. Separator may also be a dot or a space.)
Next diff →

Revision as of 12:14, 4 April 2016

Contents

Information

This function takes an integer, and returns a string formatted with commas (','), to make it easier to read. This can be very useful for scripts that use money, such as a lottery script.

Parameters:
(number)
numberThe integer you wish to format


Return Values:

A string with commas placed after every three numbers
AddCommasToInt(1234567);


Author: Puffmac. Edited by Kar and WestSide

Example

AddCommasToInt(1234567); // Returns 1,234,567
AddCommasToInt(1234);    // Returns 1,234
AddCommasToInt(123);     // Returns 123

Definition

stock AddCommasToInt(number)
{
    new
        tStr[16]; // Up to 9,999,999,999,999
 
    new number2 = number;
    if(number < 0) number = number * -1;
 
    format(tStr, sizeof(tStr), "%d", number);
 
    if(strlen(tStr) < 4)
 	return tStr;
 
    new
        iPos = strlen(tStr),
        iCount = 1;
 
    while(iPos > 0)
    {
	if(iCount == 4)
	{
	    iCount = 0;
	    strins(tStr, ",", iPos, 1);
    	    iPos++;
        }
        iCount++;
        iPos--;
    }
    if(number2 < 0) format(tStr, sizeof(tStr), "-%s", tStr);
    return tStr;
}


Version by DeimoS

Definition

stock AddCommasToInt(number, delimiter[2] = ".")
{
	new int_string[10+3+1+1];
	/*
            The maximum value for the Integer: "-2147483647" to "2147483647"
            Consequently, transmit greater than this value as a parameter impossible (only if we make "number" parameter as string)
            Declare 10 cells for the number and 3 cells for the delimiters for the largest possible number and 1 cell
            for minus and 1 and cell for the null-character.
	*/
 
	format(int_string, sizeof(int_string), "%d", number >= 0 ? number : -number); //If the number is positive - we write it in the usual way. Otherwise, convert it to a positive number, adding a minus
 
 
	new value = strlen(int_string); // Write in "i" length of the string with the our number
 
	switch(value)
	{
		case 4..6: // If the number has passed from 4 up to 6 characters, add a delimiter
					strins(int_string, delimiter, value-3,1);
		case 7..9: // From 7 to 9 characters - two delimiters
					strins(int_string, delimiter, value-3,1), 
					strins(int_string, delimiter, value-6,1);
		case 10..12: // From 10 to 12 characters - three delimiters
					strins(int_string, delimiter, value-3,1), 
					strins(int_string, delimiter, value-6,1), 
					strins(int_string, delimiter, value-9,1);
	}	
	if(number < 0) strins(int_string, "-", 0); // If the number is negative, it return him minus
	return int_string;
}