First, preface
You've learned the string in Scala before, and then you're learning Scala's numbers.
Second, Numbers
In Scala, all numeric types, such as Byte,char,double,float,int,long,short, are objects, and the seven number types inherit the Anyval trait, and these seven number types have the same range as in Java. While the unit and Boolean are considered to be non-numeric value types, Boolean has false and true two values, you can get the maximum value for each number type.
Complex numbers and dates
If you need a more powerful number class, you can use Spire,scalalab.
If you need a more powerful date class, you can use Joda time,nscala-time.
2.1 Parsing numbers from a string
1. Questions
You want to convert the string type to a numeric type.
2. Solution
Use the to* method of string to convert a string into a corresponding number.
The to* method may throw a NumberFormatException exception when conversion is not possible .
You can use strings directly to create bigint and BigDecimal instances (you may also throw exceptions)
Processing base and cardinality
If you do not calculate with 10 as the base (decimal) in the calculation, and you want to use a different binary, the ToInt method of the Int class does not allow incoming base and cardinality, you need to use the parseint method, parseint can convert the string to a value under the specified binary
You can also use implicit conversions to accomplish the above functions
3. Discussion
Since there is no check exception in Scala, you do not need to declare throws NumberFormatException in the method . But in order for the caller to understand that the method might throw an exception, you can use the throws annotation
@throws= S.toint
More generally, use option/none/some for pattern matching in Scala to handle
def toint (s:string): option[int] = { try { Some (s.toint) catch { Case e:numberformatexception = None }}
At this point you can use different methods to invoke the ToInt method
// 1 // 0
Another way to use it is to use a matching expression
ToInt (astring) match { case Some (n) = println (n) case None = println ("boom! That wasn ' t a number. " )}
You can also use the following to extract the value directly
Val result = ToInt (astring) match { case Some (x) + x Case None = > 0 }
2.2 Conversions between digital types
1. Description of the problem
You want to convert from one number type to another number type, such as from int to double.
2. Solution
Unlike Java, which uses the cast method, the To* method provided by the numeric type can be used directly in Scala.
3. Discussion
In Java, you need to force conversions to convert a double type to an int type
int a = (int) 100.00;
But in Scala, you can use the To* method to do the above conversions, and if you want to avoid conversion errors, use the IsValid method to test if you can convert
2.3 Overriding the default type
1. Description of the problem
When you assign a value to a variable, Scala automatically assigns the appropriate type to the variable, and when you create a number field, you need to override the default type.
2. Solution
If you assign 1 to variable A, then a defaults to int type
The following example overrides the default type
Another method is to use the type comment variable
You can also define it on the left side of the equals sign
You can also add 0x or 0X in front of the numbers to create hex shaping
3. Discussion
When creating an object instance, you should be aware of the following syntax structure
var [name]:[type] = [Initial value]
When you initialize the Var field of a numeric type, you can use a placeholder, whose value defaults to 0, and the placeholder is only valid when the class is defined, not at other times, as defined in the method's internal does not work
class Foo { // Define initial value // default = 0}
However, in a method, you can use the following methods
null. asinstanceof[string]
Of course, a better approach is to use option/none/some pattern matching, which avoids null values
2.4 Replacement + + 、--
1. Description of the problem
In other languages, you can use + + 、--to increase by 1, minus 1, however, there is no + + 、--operator in Scala
2. Solution
Because the Val type variable is immutable, the addition or subtraction operation is not possible, but the Var type is variable and can be used for addition or subtraction using the + =,-= method
Similarly, you can use the *=,/= method for multiplication, Division operations
It is worth noting that + =,-=, *=,/= are not operators, but methods, they are the methods implemented on the var int variable.
3. Discussion
The + =,-=, *=,/= methods can also be used on other numeric types
2.5 Comparing floating point numbers
1. Description of the problem
You need to compare two floating-point numbers, but in some other programming languages, they should be equal to two floating-point numbers
2. Solution
In Java and many other languages, you can solve this problem by creating a method that specifies the accuracy of the comparison, which is approximately equal to the method
def ~= (x:double, y:double, precision:double) = { iftrueelsefalse }
3. Discussion
When a floating-point number is calculated, 0.1 + 0.1 equals 0.2, but 0.1 + 0.2 is not equal to 0.3
This small error makes the comparison of two floating-point numbers a real problem.
Therefore, you need to customize the comparison precision function to compare two floating-point numbers for equality, you can define implicit conversions, and then you need to be introduced. Or put the method in the object, so that you can call directly
object Mathutils { ~= (x:double, y:double, precision:double) = { iftrue Else false }
The ~= method is then directly compared by calling the Mathutils
println (Mathutils.~= (A, B, 0.000001))
2.6 Handling Large numbers
1. Description of the problem
You are writing an application that needs to use very large integers or decimal numbers
2. Solution
You can use the bigint or BigDecimal class
Unlike its corresponding classes in Java, these classes support all operators for which you use numeric types
You can also convert them to other number types
To avoid errors, you can also test before conversion
3. Discussion
Although BigInt and BigDecimal in Scala are supported by bigint and BigDecimal in Java, classes in Scala are easier to use, and they are mutable and can be manipulated like other numeric types.
2.7 Generating random numbers
1. Description of the problem
You need to create random numbers, such as test applications, perform simulations, and many other situations
2. Solution
Use Scala.util.Random to create random numbers
You can specify the maximum value of randomly generated numbers
The example above will generate a number between [0-99], and you can also generate a random float (0.0 to 1.0 floating-point numbers)
You can also generate a random double (a floating-point number between 0.0 and 1.0)
You can also specify the seed value when you create the random, or you can call the Setseed method to set it later
3. Discussion
The random class can handle all the usual uses, including generating numbers, setting the maximum value, setting the seed value, or generating random characters
Scala can generate a random length number, which is useful when testing
You can also generate floating-point numbers of random lengths
2.8 Creating a numeric range, list, or array
1. Description of the problem
You need to create a number range, list, or array, such as for loop or for testing purposes
2. Solution
Use the Int class method to create a number range
You can also customize the spacing
3. Discussion
In Scala, you can easily create a range of numbers and easily convert them to lists or array types.
The better way is as follows
2.9 Formatting numbers and currencies
1. Description of the problem
You want to format numbers and currencies to control the decimal point and the comma, especially for print output.
2. Solution
For simple numeric formatting, you can use the F string interpolation mentioned in the previous blog post
An easy way to add commas is to call the Getintegerinstance method of the Java.text.NumberFormat class
You can specify a region when using the Getintegerinstance method
You can use the GetInstance method when working with floating-point numbers
For currency formats, you can use the Getcurrencyinstance method
The following methods can handle international currency
3. Discussion
This paper mainly discusses the use of Java related classes to format numbers and currencies, or the use of bigdecimal to handle currency formatting problems.
Iii. Summary
This blog post learns about the operations of the digital class, and you can see that Scala is much simpler than Java and is seamlessly compatible with Java. And thank you for watching the Garden friends ~
"Scala" Scala's numbers