This blog post contains a collection of Scala number and date examples. I created most of these in the process of writing the Scala Cookbook. Unlike the Cookbook, I don’t describe the examples here much at all, I just show the examples, mostly as a reference for myself (and anyone else that can benefit from them).
Scala numeric types
Scala has these numeric types:
Byte Char Double Float Int Long Short
Their maximum values are shown here:
Byte.MaxValue // Byte = 127 Char.MaxValue // (output omitted) Double.MaxValue // Double = 1.7976931348623157E308 Float.MaxValue // Float = 3.4028235E38 Int.MaxValue // Int = 2147483647 Long.MaxValue // Long = 9223372036854775807 Short.MaxValue // Short = 32767
Scala numeric conversions
You can convert a Scala string to each of the numeric types:
"1".toByte // Byte = 1 "100".toDouble // Double = 100.0 "100".toFloat // Float = 100.0 "100".toInt // Int = 100 "1".toLong // Long = 1 "1".toShort // Short = 1 // exceptions "foo".toInt // java.lang.NumberFormatException: For input string: "foo" "19.45".toInt // java.lang.NumberFormatException: For input string: "19.45"
More data conversions:
19.toByte // Byte = 19 19.toDouble // Double = 19.0 19.toFloat // Float = 19.0 19.45.toInt // Int = 19 19.toLong // Long = 19 19.toShort // Short = 19
Setting numeric values implicitly and explicitly
Scala normally determines data types implicitly, but you can also set them explicitly:
// implicit val a = 0 // Int = 0 val b = 1.0 // Double = 1.0 // explicit val a: Byte = 0 // Byte = 0 val a: Double = 0 // Double = 0.0 val a: Float = 0 // Float = 0.0 val a: Int = 0 // Int = 0 val a: Long = 0 // Long = 0 val a: Short = 0 // Short = 0 // this works val a = 1d // Double = 1.0 val a = 1f // Float = 1.0 // octal (preceding '0') val a = 040 // Int = 32 // hex (leading 0x or 0X) val a = 0x20 // Int = 32 // hex to Long val a = 0x20L // Long = 32
There is no ++
and --
:
// use += and -= var a = 1 a += 1 // 2 a -= 1 // 1 // multiplication and division a *= 2 // 2 a *= 2 // 4 a /= 2 // 2
Scala BigInt and BigDecimal
Scala includes BigInt
and BigDecimal
support:
var b = BigInt(1234567890) // scala.math.BigInt = 1234567890 var b = BigDecimal(123456.789) // scala.math.BigDecimal = 123456.789 // support numeric operators b+b // scala.math.BigInt = 2469135780 b*b // scala.math.BigInt = 1524157875019052100 b += 1 // 1234567891 // convert to other numeric types b.toInt // Int = 1234567891 b.toLong // Long = 1234567891 b.toFloat // Float = 1.23456794E9 b.toDouble // Double = 1.234567891E9 // test them b.isValidByte // Boolean = false b.isValidChar // Boolean = false b.isValidInt // Boolean = true b.isValidShort // Boolean = false
Random numbers
You can do all the usual random number things:
var r = scala.util.Random r.nextInt // Int = -1323477914 r.nextInt(100) // Int = 58 // between 0.0 and 1.0, no args req'd r.nextFloat // Float = 0.50317204 // between 0.0 and 1.0, no args req'd r.nextDouble // Double = 0.6946000981900997 // seed r.setSeed(1945) // random characters r.nextPrintableChar // Char = H r.nextPrintableChar // Char = r
Number formatting
There are a wide variety of ways to format numeric output:
"%1.5f".format(pi) // String = 3.14159 "%1.3f".format(pi) // String = 3.142 // zero-filled "%06.2f".format(scala.math.Pi) // String = 003.14 // currency "$%.2f".format(123.456789) // String = $123.46 "$%.2f".format(1234.56789) // String = $1234.57 "$%.2f".format(12345.6789) // String = $12345.68 val format = java.text.NumberFormat.getCurrencyInstance println(format.format(123.456789)) // $123.46 println(format.format(1234.56789)) // $1,234.57 println(format.format(12345.6789)) // $12,345.68 println(format.format(123456.789)) // $123,456.79 // locale import java.util.Locale import java.util.Currency val de = Currency.getInstance(new Locale("de", "DE")) format.setCurrency(de) println(format.format(123456.789)) // EUR123,456.79
You’ll find math functions under scala.math:
import scala.math._ sqrt(4) // Double = 2.0 pow(2,1) // Double = 2.0 abs(-1) // Int = 1 pow(2,2) // Double = 4.0 pow(2,3) // Double = 8.0 round(19.49) // Long = 19 ceil(19.1) // Double = 20.0 floor(19.1) // Double = 19.0 // Pi and E scala.math.Pi // Double = 3.141592653589793 scala.math.E // Double = 2.718281828459045
Scala date and time examples
You can use Java classes for date and time handling:
import java.text.SimpleDateFormat import java.util.Calendar val today = Calendar.getInstance.getTime // create the date/time formatters val minuteFormat = new SimpleDateFormat("mm") val hourFormat = new SimpleDateFormat("hh") val amPmFormat = new SimpleDateFormat("a") val currentHour = hourFormat.format(today) // 12 val currentMinute = minuteFormat.format(today) // 29 val amOrPm = amPmFormat.format(today) // PM
You can also use the nscala-time library and Joda time:
import com.github.nscala_time.time.Imports._ import org.joda.time.Days // from <a href="http://alvinalexander.com" title="http://alvinalexander.com">http://alvinalexander.com</a> object DaysUntilChristmas extends App { // 1: get the current date and time val now = DateTime.now // 2: get a date to represent Christmas val xmas = (new DateTime).withYear(2013) .withMonthOfYear(12) .withDayOfMonth(25) // 3: determine the number of days from now until xmas val daysToXmas = Days.daysBetween(now, xmas).getDays // 4: print the result println(s"daysToXmas = $daysToXmas") // bonus: what day is 200 days from now? val nowPlus200 = now + 200.days println(s"nowPlus200 = $nowPlus200") }
this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |
Summary
In summary, I hope these Scala number/numeric examples have been helpful. I’ll keep updating this blog post as I come up with more examples.