How to display a number with always 2 decimal points using BigDecimal?

BigDecimal is immutable, any operation on it including setScale(2, BigDecimal.ROUND_HALF_UP) produces a new BigDecimal. Correct code should be BigDecimal bd = new BigDecimal(1); bd.setScale(2, BigDecimal.ROUND_HALF_UP); // this does change bd bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP); System.out.println(bd); output 1.00 Note – Since Java 9 BigDecimal.ROUND_HALF_UP has been deprecated and you should now use RoundingMode.ROUND_HALF_UP.

Why is this simple calculation of two doubles inaccurate? [duplicate]

Floating point numbers (in this case doubles) cannot represent decimal values exactly. I would recommend reading David Goldberg’s What every computer scientist should know about floating-point arithmetic This applies to all languages that deal with floating point numbers whether it be C#, Java, JavaScript, … This is essential reading for any developer working with floating … Read more

Point in Polygon algorithm giving wrong results sometimes [closed]

Have been there 🙂 I also travelled through Stackoverflow’s PiP-suggestions, including your reference and this thread. Unfortunately, none of the suggestions (at least those I tried) were flawless and sufficient for a real-life scenario: like users plotting complex polygons on a Google map in freehand, “vicious” right vs left issues, negative numbers and so on. … Read more

How to get largest possible precision? (Python – Decimal)

Trying to do this is a mistake. Throwing more precision at a problem is a tempting trap for newcomers to floating-point, but it’s not that useful, especially to this extreme. Your operations wouldn’t actually require the “largest possible” precision even if that was a well-defined notion. Either they require exact arithmetic, in which case decimal.Decimal … Read more

Is there a reliable way in JavaScript to obtain the number of decimal places of an arbitrary number?

Historical note: the comment thread below may refer to first and second implementations. I swapped the order in September 2017 since leading with a buggy implementation caused confusion. If you want something that maps “0.1e-100” to 101, then you can try something like function decimalPlaces(n) { // Make sure it is a number and use … Read more