I want to change 3.4499999999999… to 3.45.
Math.round or ceil is not for this case.
Any idea? [import]uid: 65906 topic_id: 17086 reply_id: 317086[/import]
first things first, Mathematically, 3.49 cannot be rounded off to 3.45, it is wrong on many levels…
However if you want that 3.449999999 be rounded off to 3.45 then here’s how
local number = 3.4499999
print(math.floor((number+0.005)\*100)/100)
add the 0.005 so that the 3rd digit after the decimal if it is 5 or more will affect the second digit after the decimal.
number + 0.005 ==> 3.4499999 + 0.005 = 3.4549999
Since the math.round, math.floor and math.ceil do not work with decimal numbers, we convert them into integers, so to get 2 decimal precision, we multiply that by 100,
3.4549999 * 100 ==> 345.49999
this is what we are after, and to chop off the trailing decimals, we just use the floor function so we get
floor(345.49999) ==> 345
and to get it back to the way we had the number ,we divide it back by 100
354/100 == > 3.45
cheers,
?
[import]uid: 3826 topic_id: 17086 reply_id: 64171[/import]
@JayantV
Thanks for your reply.
As expected…it is complicated.
I will try on your way. Thanks again [import]uid: 65906 topic_id: 17086 reply_id: 64235[/import]
Hey Sleepysheep, just wondering, are you in school? you find this complicated? this is simple school math.
how does the answer feel, minus all the explanation?
local number = 3.4499999
print(math.floor((number+0.005)\*100)/100)
does it look any easier?
cheers,
?
[import]uid: 3826 topic_id: 17086 reply_id: 64236[/import]
Why use math.floor? math.round makes it more simple:
[lua]local number = 3.4499999
print(math.round(number*100)/100) [import]uid: 13632 topic_id: 17086 reply_id: 64258[/import]
@JayantV
Sorry to make some confusion with my English.
“Complicated”, which I mean is, I have to calculate by myself. It is kind of troublesome but of course it is not hard. Sorry, I used wrong English word.
Your answer is ++ for me!
[import]uid: 65906 topic_id: 17086 reply_id: 64275[/import]