double

Java int, double, float, and mixed-type arithmetic rules

Table of Contents1 - The answer2 - More Java division and arithmetic rules3 - Summary

Java FAQ: What are the rules about Java arithmetic (multiplication, division) involving mixed data types?

While working on a math problem in Java just a little while ago, I realized that I wasn’t comfortable with the Java mixed-type division rules. That is, I wondered if the result of this equation:

3 / 2

the same as the result of this equation:

3 / 2.0

or this equation:

3.0 / 2.0

Java: How to round a float or double to an integer

Java math FAQ: How do I round a float or double to an integer in Java?

Solution: Use Math.round() to round a float (or double) to the nearest integer (int) in Java.

You can see how this works in the examples that follow, where the result is shown in the comment after each line:

How to compare floating-point numbers in Scala

Scala FAQ: I need to compare two floating-point numbers in Scala, but as in some other programming languages, two floating-point numbers that should be equivalent may not be; how do I comparison floating-point numbers?

Solution

As in Java and many other languages, you solve this problem by creating a method that lets you specify the precision for your comparison. The following Scala “approximately equals” method demonstrates the approach:

How to convert between numeric types in Scala

Scala FAQ: How do I convert between numeric types in Scala, such as from Int to Long, Int to Double, etc.?

Solution

Instead of using the “cast” approach in Java, use the to* methods that are available on all of Scala’s numeric types. These methods can be demonstrated in the REPL (note that you need to hit the [Tab] key at the end of the first example):

Scala: How to parse a number from a String

Scala FAQ: How do I parse a number (Int, Long, Float, etc.) from a String in Scala?

Solution

Use the to* methods that are available on a String (courtesy of the Scala StringLike trait):

MySQL Java mappings (Decimal to BigDecimal, etc.)

As I get back into working with a MySQL database in a Java (Scala, actually) development project and also in adding functionality to Cato, I found these MySQL to Java data type mappings, via this link:

Scala data types (bit sizes, ranges, and docs)

Scala FAQ: What are the Scala data types? How many bits do they use to store their data, and what is the range of those data types?

Courtesy of the excellent book, Programming in Scala, here is a list and description of the Scala data types, including bit sizes and data ranges:

Java: How to convert strings to numbers

Question: How do I convert a String to an int or a float?

Short answer: You want to use the Integer.parseInt() or Float.parseFloat() methods.

Here's an example Java program that shows how to convert a String to either an int or a float: