Better way to convert any number to C string

B

In the previous version of number to C string converter, we could only convert integer numbers. Even if it was faster, sometimes it is crucial to use floating point numbers in our projects. This version of num_to_string function provides conversion of both positive and negative numbers as well as floating point numbers.

const char * num_to_string( double value )
{
	char * result;
	double temp_value;
	double prt_int, prt_frac;
	int cnt_fract = 0, cnt_int = 0, tmp_ivalue, ps_result = 0;

	temp_value = value;
	while ( ( prt_frac = modf( temp_value, &prt_int ) ) != 0 && cnt_fract++ < 6 )
		temp_value *= 10;

	temp_value = value;
	prt_frac = modf( temp_value, &prt_int );
	while ( prt_int != 0 )
		prt_frac = modf( ( temp_value / pow( 10, ++cnt_int ) ), &prt_int );

	cnt_int = cnt_int == 0 ? 1 : cnt_int;

	result = ( char * ) malloc( ( ( value < 0 ? 1 : 0 ) + cnt_int + ( cnt_fract == 0 ? 0 : cnt_fract + 1 ) + 1 ) * sizeof( char ) );

	*result = '-';
	ps_result = ( value < 0 ? 1 : 0 );

	value = fabs( value );

	prt_frac = modf( value, &prt_int );

	tmp_ivalue = ( int ) prt_int;

	while ( cnt_int-- != 0 )
	{
		result [ ps_result++ ] = ( ( tmp_ivalue - ( tmp_ivalue % ( int ) pow( 10, cnt_int ) ) ) / ( int ) pow( 10, cnt_int ) ) + 48;
		tmp_ivalue -= ( tmp_ivalue - ( tmp_ivalue % ( int ) pow( 10, cnt_int ) ) );
	}

	result [ ps_result ] = '.';
	ps_result += cnt_fract == 0 ? 0 : 1;

	tmp_ivalue = ( int ) ( prt_frac*pow( 10, cnt_fract ) + ( double ) 5 / pow( 10, cnt_fract ) );

	while ( cnt_fract-- != 0 )
	{
		result [ ps_result++ ] = ( ( tmp_ivalue - ( tmp_ivalue % ( int ) pow( 10, cnt_fract ) ) ) / ( int ) pow( 10, cnt_fract ) ) + 48;
		tmp_ivalue -= ( tmp_ivalue - ( tmp_ivalue % ( int ) pow( 10, cnt_fract ) ) );
	}

	result [ ps_result ] = 0;

	return result;
}
Disclaimer: The present content may not be used for training artificial intelligence or machine learning algorithms. All other uses, including search, entertainment, and commercial use, are permitted.

Categories

Tags