Re: rounding problem

new topic     » goto parent     » topic index » view thread      » older message » newer message

George Walters wrote:
> 
> Ricardo M. Forno wrote:
> > them by means of the float() function [truncate: z = floor(x * 10000);
> > round:
> > floor(x * 10000 + 0.5)]. When printing them, divide them into 10,000,
> 
> This is exactly what my round functin does, but produces a different result
> than
> sprintf. I would like to know how sprintf does it's rounding. Anyone know?
> 
> }}}
<eucode>
> global function round(atom a, integer b)
> atom f
> 
> 	if b < 0 then
> 		return a -- invalid argument, do nothing
> 	elsif b = 0 then
> 		return floor(a+.5)
> 	else
> 		f = power(10,b)
> 		return floor(a * f +.5 / f)
> 	end if
> 	
> end function
> </eucode>
{{{


Please check the sligth change I made to your round() routine.
Division by 10,000 should be made *after* rounding.
It is named round1(). I also included my RoundCents routine from my
General Functions package.
Regards.

include genfunc.e -- General Functions

global function round(atom a, integer b)
atom f

	if b < 0 then
		return a -- invalid argument, do nothing
	elsif b = 0 then
		return floor(a+.5)
	else
		f = power(10,b)
		return floor(a * f +.5 / f)
	end if
	
end function

global function round1(atom a, integer b)
atom f

	if b < 0 then
		return a -- invalid argument, do nothing
	elsif b = 0 then
		return floor(a+.5)
	else
		f = power(10,b)
		return floor(a * f +.5) / f
	end if
	
end function
atom x
for i = 1 to 10 do
    x = rand(100) / 6.56745321
printf(1, "%10.10f %10.10f %10.4f %10.4f %10.4f\n", {x, round(x, 4),
    round(x, 4), round1(x, 4), RoundCents(x, 10000)})
end for


new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu