Official Soldat Forums
Server Talk => Scripting Discussions and Help => Topic started by: DarkCrusade on July 14, 2013, 04:45:17 am
-
Hello, I am encountering a problem rounding floats with Soldat's scriptcore due to no implementation of the powerfunction. I tried to write my own, but apparently failed..
function power(x,y:integer):single;
begin
if y = 1
then result := x
else result := x * power(x,y-1);
end;
function round2(const num:single; const places:longint):single;
var t:single;
begin
t := power(10,places);
result := round(num*t)/t;
end;
procedure test();
var x:single;
begin
x := 3.5000000000000000;
x := round2(x,4);
writeln(floattostr(x)); // Outputs 3.5000000000
end;
Could anyone help me here? Where do I go wrong?
-
Are you just trying to round it up/down? Or what exactly?
-
I want all numbers to be rounded to two decimal places. All the floating values I use use no more than two decimal places, and having console outputs of 20 iterations of '0' is simply ugly.
-
When you mean round, are you trying to display the output of 3.5 rounded to 4 dp as 3.5000 instead of printing out a bunch of extra zeros, or is there something else which is not working? You weren't very clear.
If you are trying to print fewer zeros, you will have to manipulate the string, what you are doing in your code will have no effect on the number that is stored if the number has the same value rounded or not
-
http://bugs.soldat.pl/view.php?id=15
-
@chutem: Yes, I want the extra zeros removed. My English fails me sometimes. The problem is that I receive a string value (take 3.5 for an example) which I want to convert to a single. The function StrToFloat will store the extra zeros as well, though, and I see no reason why I should iterate through the complete string until I find the part where only zeros are stored.
My new approach was this:
function floattostr2(const val:single):string;
var i,j,lastnum:byte;
begin
result := floattostr(roundto(val,2));
for i := 1 to length(result) do
if copy(result,i,i) = '.' then begin
for j := i+1 to length(result) do
if copy(result,j,j) <> '0' then lastnum := j;
result := copy(result,1,lastnum);
end;
end;
But it failed as well.
-
Hello, I have just written this simple function, but I'm not sure this is exactly what you want to achieve. This function truncates a float to two decimal digits and returns that value as a string.
function FloatToStr2(val: single):string;
var
i: integer;
temp_str: string;
begin
temp_str := FloatToStr(val); //get the float with all zeros
//find the dot
for i := 1 to length(temp_str) do begin
if temp_str[i] = '.' then begin
result := copy(temp_str, 1, i+2);
break;
end;
end;
end;
Hope this helps!
-
Works. I am *headdesking* because I did not think of that.. ;)