[Small story] Misleading method name (a story that wasted time due to setScale.

Introduction

The Big Decimal class is hard to use unless you are involved in work that deals with the precision of numbers. So, when I played with it for the first time in a long time, I was so addicted to it that I wasted my time.

Related methods

BigDecimal setScale(int newScale) setScale(int newScale, int roundingMode) setScale(int newScale, RoundingMode roundingMode)

Program specifications

Display the processing result with one decimal place

program

public static void main (String[] args) {
    
    BigDecimal deci = new BigDecimal("1.2345");
    
    System.out.println("deci 1:" + deci);
    
    deci.setScale(1, BigDecimal.ROUND_DOWN);
    
    System.out.println("deci 2:" + deci);
    
}

Execution result

deci 1:1.2345 deci 2:1.2345

??? By the way, with this execution result, those who are polite will be JavaDoc first, and those who are familiar with it will be "Ah ...", but I wasted this and that, It took about 20 minutes to resolve it. .. .. (> <). why? When. .. ..

Program 2

public static void main (String[] args) {
	
	BigDecimal deci = new BigDecimal("1.2345");
	
	System.out.println("deci     1 :" + deci);
	
	deci.setScale(1, BigDecimal.ROUND_DOWN);
	
	System.out.println("deci     2 :" + deci);

	BigDecimal deciDecci = deci.setScale(1, BigDecimal.ROUND_DOWN);

	System.out.println("deciDecci  :" + deciDecci);
}

Execution result 2

deci 1 :1.2345 deci 2 :1.2345 deciDecci :1.2

Conclusion

After all, setScale was a method that returned a return value rather than changing the contents of the instance. .. .. I thought I wanted it to be named like toString (), but I should have carefully looked at JavaDoc once. There are various sets and setXXX in the Calendar class and so on.

Recommended Posts

[Small story] Misleading method name (a story that wasted time due to setScale.
A story that took time to establish a connection
The story that docker had a hard time
A story that I had a hard time trying to build PHP 7.4 on GCE's CentOS 8
A small story that is sometimes useful in Maven
How to create a method
A story that I struggled to challenge a competition professional with Java
Add a time stamp to the JAR file name in Gradle
Let's write a code that is easy to maintain (Part 2) Name
How to operate IGV using socket communication, and the story of making a Ruby Gem using that method