官术网_书友最值得收藏!

Floating point literals

Floating point literals include a decimal point that can be at the beginning or in between decimal digits, but not at the end. What we mean by this is that if you write the following statement, it won't work:

scala> val a = 1. //Not possible!

It won't work if you try this in Scala REPL, the expression will be continued in the next line. A quick trick: if you give two more returns in REPL, it'll start a new command. But this is how we cannot create a floating point in Scala, so now let's see how we can define a Double or a Float value. By default, Scala treats decimal point values as Double, if we don't specify it to be a Float:

scala> val aDoubleByDefault = 1.0
aDoubleByDefault: Double = 1.0

We can specify our values to be of Float type the same way we did for Long literals but with an invisible asterisk. Let's check that condition:

scala> val aFloat: Float = 1.0 //Compile Error!
scala> val aFloat: Float = 1.0F //Works
scala> val aFloat: Float = 1.0f //Works

All three were supposed to work and give us Float values but unfortunately only the latter two give back a Float value. The first one is going to give a type mismatch error stating what you specified is a Float, and what you bound is of Double type. So in Scala, to specify a literal to be of Float value, we'll have to give suffix f or F:

scala> val aFloat: Float = 1.0
<console>:11: error: type mismatch;
found : Double(1.0)
required: Float
val aFloat: Float = 1.0
^

Then we can optionally append D or d for a Double value, but we hardly do so. Floating point literals can also have an exponential part in it. That is going to be an e or E followed by an optional + or -, then few digits. E or e indicates the power of 10. So a value 3.567e2 means 3.567 multiplied by 10^2, which is 356.7, that is, 3.567 times 100.

主站蜘蛛池模板: 许昌市| 二连浩特市| 潮安县| 迁西县| 霍州市| 福贡县| 兴城市| 三江| 珠海市| 敦煌市| 望谟县| 紫阳县| 铜梁县| 沧州市| 建瓯市| 庆城县| 河津市| 婺源县| 阿勒泰市| 巩义市| 青海省| 广宗县| 盘山县| 信宜市| 邵阳县| 盐亭县| 武宁县| 霞浦县| 新郑市| 屯昌县| 郧西县| 昌邑市| 磐安县| 嘉荫县| 左云县| 牟定县| 孟州市| 额尔古纳市| 甘肃省| 镇平县| 三门县|