Skip to content. | Skip to navigation

Personal tools

lcu/math.cpp

lcu/math.cpp

lcu/math.cpp

#include <math.h>
#include <stdio.h>
#include <stdlib.h>

/////////////////////////////////////////////////////////////////////////////
// round - returns a rounded int of the given float
long round(float data)
{
	long temp;
  float ftemp;

  ftemp = fmod(data,1.0);
	if (ftemp > 0.5)
		temp = data + 1;
	else if (ftemp < -0.5)
		temp = data - 1;
  else
  	temp = data;
	return(temp);
}

/////////////////////////////////////////////////////////////////////////////
// FormatFloat - Formats a float into a string
char * FormatFloat(char * s,float data,int sign,int zero,int width,int prec)
// Resulting string returned in s, pass float to be formatted in data
// set sign to 1 to always append a sign (+ and -)
// set sign to 2 to append a blank if positive, - if negative
// set zero to 1 to always pad left with zeroes
// set width to the total width of the field desired
// set prec to the number of digits right of the decimal
{
	long a,b,i,left,righttens,lefttens,temp,negflag;

  negflag =  (data < 0);
  if (negflag || sign)
  	left = width - prec - 2;
  else
  	left = width - prec - 1;

  righttens = 1;
  for (i=1;i<=prec;i++)
  	righttens = righttens * 10;
  lefttens = 1;
  for (i=1;i<=left;i++)
  	lefttens = lefttens * 10;

  temp = round(data * (float)righttens);
  a = temp / righttens;
  b = abs(temp) % righttens;

  if (a > lefttens - 1)
  {
  	a = lefttens - 1;
    b = righttens - 1;
  }
	if (a < -(lefttens - 1))
  {
  	a = -(lefttens - 1);
    b = righttens - 1;
  }

  if (zero)
  {
  	switch (sign)
    {
    	case 1: sprintf(s,"%+0*d.%0*d",width-prec-1,a,prec,b);break;
    	case 2: sprintf(s,"% 0*d.%0*d",width-prec-1,a,prec,b);break;
      default:sprintf(s,"%0*d.%0*d",width-prec-1,a,prec,b);break;
    }
  }
  else
  {
  	switch (sign)
    {
    	case 1: sprintf(s,"%+*d.%0*d",width-prec-1,a,prec,b);break;
    	case 2: sprintf(s,"% *d.%0*d",width-prec-1,a,prec,b);break;
      default:sprintf(s,"%*d.%0*d",width-prec-1,a,prec,b);break;
    }
  }
  return(s);
}

Generated by GNU Enscript 1.6.5.2.
Document Actions