Earlier, I found myself writing a script where I needed to be able to round a value to so many decimal places. I do not believe Graal has a built-in method of doing this.
I wrote this code to do it. I hope that somebody may find it useful, either to use or to learn from.
NPC Code:
//#CLIENTSIDE
if (playerchats) {
tokenize #c;
if (strequals(#t(0),dp)) {
// ***Save the data first
setstring this.first,#t(1); //<- INPUT NUMBER TO BE ROUNDED
this.places=strtofloat(#t(2)); //<- NUMBER OF DECIMAL PLACES TO ROUND TO
// ***Split the data so that it can be taken into two parts (part1.part2)
tokenize2 .,#s(this.first);
setstring this.second_1,#t(0);
setstring this.second_2,#t(1);
// ***Then split up the second half of the data so we can work with it
setstring this.third_1,#e(0,this.places,#s(this.second_2)); // All the decimal places
setstring this.third_2,#e(0,this.places-1,#s(this.second_2)); // All the decimal places minus 1
setstring this.third_3,#e(this.places,1,#s(this.second_2)); // The decimal place after the round value
setstring this.third_4,#e(this.places-1,1,#s(this.second_2)); // The decimal place at the round value
// ***Now start reconstructing the decimal point
// ***The first instance here builds the number back up as it was
// ***The second instance builds it back as if the last decimal place has a number
// ***lower than 5 after it
// ***But first we need to check if we were given less numbers than DP specified
if (strtofloat(#s(this.third_3))>=5) setstring this.result,#s(this.second_1).#s(this.third_2)#s(t his.third_4);
else setstring this.result,#s(this.second_1).#s(this.third_2)#v(s trtofloat(#s(this.third_4))-1);
// ***Now check whether the result was valid and then set the this.result value
if (strequals(#e(strlen(#s(this.result))-2,2,#s(this.result)),-1)) setstring this.final,#s(this.first);
else setstring this.final,#s(this.result);
this.final = strtofloat(#s(this.final));
// ***And give the player the value via chattext
setplayerprop #c,#s(this.final);
}
}
It works at the moment by saying "dp <number> <places>" which will round <number> to so many decimal <places>. If you specify too many decimal <places> for the <number>, it simply returns the <number> you originally gave it.
I do realise that there is alot of unnecessary code in there, but it may, again, help somebody learn.
It returns the final value in both the string and variable `this.final', as you can most likely see.