Format a number with thousand separator characters in Rust

Category: rust, year: 2021

The following code function snippet is an example of how to format a number (already in String/&str form) with thousand separator characters in Rust:

pub fn thousand_separate_string_number(string_val: &str) -> String {
    let mut s = String::new();
    let mut local_copy = string_val.to_string();
    
    let decimal_pos = local_copy.rfind('.');
    if let Some(pos) = decimal_pos {
        // deal with any decimal place digit and following digits first
        s.push_str(&string_val[pos..]);
        local_copy = string_val[..pos].to_string();
    }
    
    let chrs = local_copy.chars().rev().enumerate();
    for (idx, val) in chrs {
        if idx != 0 && idx % 3 == 0 {
            s.insert(0, ',');
        }
        s.insert(0, val);
    }
    s
}


Format a number with thousand separator characters in C++

Category: cpp, year: 2019

The following code function snippet is an example of how format a number (already in std::string form) with thousand separator characters in C++:

Note: it doesn’t currently support numbers with decimal places, only integer-formatted numbers.

std::string formatNumberThousandsSeparator(const std::string& value)
{
	std::string final;
	int i = value.size() - 1;
	unsigned int count = 0;
	for (; i >= 0; i--)
	{
		final += value[i];

		if (count++ == 2 && i != 0)
		{
			final += ",";
			count = 0;
		}
	}

	std::reverse(final.begin(), final.end());

	return final;
}



Archive
Full Index

linux (4)
cpp (3)
rust (2)
macos (1)
matplotlib (1)
unix (1)


Tags List