[R] why the base::round(0.015, 2) returns 0.02?

Rui Barradas ruipb@rr@d@@ @ending from @@po@pt
Wed Nov 28 18:55:21 CET 2018


Hello,

Your assumption that you can sprintf with 20 digits of precision is 
wrong, you only have 16 decimal digits. And

sprintf('%.16f', 0.015)
#[1] "0.0150000000000000"

0.015 == 0.0150000000000000
#[1] TRUE

This rounds to the nearest even number, 0.02 (IEEE-754).

Hope this helps,

Rui Barradas

Às 13:49 de 28/11/2018, Philipp Upravitelev escreveu:
> Dear colleagues,
> could you help me with the function base::round()? I can't understand how
> it works.
> 
> For example, when I want to round 0.015 to the second digit, base::round()
> returns 0.02.
> 
> But the real representation of the 0.015 is different:
>> sprintf('%.20f', 0.015)
> [1] "0.01499999999999999944"
>> 0.015 == 0.01499999999999999944
> [1] TRUE
>> round(0.015, 2)
> [1] 0.02
> 
> Therefore, according to the arithmetic rules, rounded 0.014 to the second
> digit is 0.01. Also, the round() function in other programming languages
> (Python, Java) returns 0.01. It is a bit counterintuitive but
> mathematically correct.
> 
> I'll be very pleased if you could help me to figure out why the
> base::round(0.015, 2) returns 0.02 and what is the purpose of this feature.
> 
> Best regards,
> Philipp Upravitelev
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list