Java Puzzles about money computing

Source: Internet
Author: User

Java Puzzles about money computing
Java Puzzles about money computing

Java Puzzles: for monetary computation, java uses int, long, or BigDecimal for computation. Generally, we use BigDecimal.

Package com.doc tor. java. puzzle; import java. math. bigDecimal;/*** @ author sdcuike *** @ time 9:26:52 on August 18 ** java Puzzles: For Money computing, java uses int, long, or BigDecimal to calculate, generally, we use BigDecimal. ** Warning: Use the BigDecimal (String) constructor instead of BigDecimal (double ). * ** In summary, avoid float and double where exact answers are required; * for monetary calculations, use int, long, or BigDecimal. * Not all decimals can be represented exactly using binary floating-point. ** There is one caveat: Always use the BigDecimal (String) constructor, * never BigDecimal (double ). the latter constructor creates an instance with the * exact value of its argument: new BigDecimal (. (1) returns a BigDecimal representing 0.1000000000000000055511151231257827021181583404541015625. **/public class TimeForAChange {public static void main (String [] args) {System. out. println (2.00-1.10); // 0.8999999999999999 System. out. println (2.00D-1.10D); // 0.8999999999999999 System. out. println (2.00F-1.10F); // 0.9 System. out. println (Double. toString (2.00D); // 2.0 System. out. println (BigDecimal. valueOf (2.00 ). subtract (BigDecimal. valueOf (1.10); // 0.9 System. out. println (BigDecimal. valueOf (2.00F ). subtract (BigDecimal. valueOf (1.10F); // 0.899999976158142 System. out. println (BigDecimal. valueOf (2.00D ). subtract (BigDecimal. valueOf (1.10D); // 0.9 System. out. println (new BigDecimal ("2.00 "). subtract (new BigDecimal ("1.10"); // 0.90 }}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.