There are in fact an infinite number of text number representations you can put in that code and still get 3.14 out (for example any digits you append to this will not change anything). The fact that it prints 3.14 does not mean that 3.14 is its exact value. The ValueOfPi is irrational (more specifically, transcendental) what follows are either approximations or infinite expressions. When converting the value to string it outputs 3.14 because that is the shortest representation that is closest to that exact value than it is to either of these 2 surrounding values. That way if you tried to parse that string representation you will get the same exact value. The downside of BigDecimal is that it is slower and more cumbersome to use (less so in Kotlin) as there isn’t built in hardware support for it.īasically when converting for output Java (which then carries over to Kotlin) will output the shortest string representation that is closer to the exact value than it is to the next representable floating point value. You can get away with int or long to represent number of pennies as long as you know that the range is limited. This is why the best advice when representing money is never use float or double and always use BigDecimal. m=314 and n=-2 give you the exact value of 3.14. Try as hard as you want you will not find any integer values for m and n that give you exactly 3.14.īigDecimal on the other hand represents numbers of the form m * 10 ^ n where m and n are integers and are essentially unbounded. Divide the number by 10 with help of ‘/’ operator to remove the rightmost digit. Get the rightmost digit of the number with help of the remainder ‘’ operator by dividing it by 10 and multiply it to the product. The difference between float and double is merely how many bits are allocated for m and n and thus how precise you can be. Get the remainder and pass the next remaining digits. Float and double can only represent values that are exactly equal to m * 2 ^ n, where m and n are taken from a subset of the set of integers. The only difference between float and double is how close you can get to the number. But I did accidentally show the float representation not the double one. It is the same for both float and double that neither can exactly represent 3.14.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |