【问题标题】:Rounding of Double value without decimal points in spark DataframeSpark Dataframe中不带小数点的Double值四舍五入
【发布时间】:2019-10-24 21:43:39
【问题描述】:

我尝试在 spark 数据框中舍入一个不带小数点的双精度值,但在输出中获得了相同的值。

下面是数据框列值。

+-----+-----+
| SIG1| SIG2|
+-----+-----+
| 46.0| 46.0|
| 94.0| 46.0|

数据框列的架构如下。

scala> df.printSchema
root
 |-- SIG1: double (nullable = true)
 |-- SIG2: double (nullable = true)

预期输出如下

+-----+-----+
| SIG1| SIG2|
+-----+-----+
| 46  |   46|
| 94  |   46|

我根据文档尝试了如下四舍五入的列

+------------------------------------------------------------------+
|ReturnType| Signature     |                            Description|
+------------------------------------------------------------------+
|DOUBLE    |round(DOUBLE a)| Returns the rounded BIGINT value of a.|

使用的代码是

val df1 = df.withColumn("SIG1", round(col("SIG1"))).withColumn("SIG2", round(col("SIG2")))

我们需要将列转换为 int/bigint 还是可以使用 round 函数本身?

提前致谢!

【问题讨论】:

  • 请不要以此为契机投反对票,正如我所提到的,我在文件中看到它是可能的并且不会发生,只是想确认一下!

标签: dataframe apache-spark apache-spark-sql rounding


【解决方案1】:

round 函数也返回双精度值,所以如果你想要 int 类型然后转换它。

scala> Seq(1.9999,2.1234,3.6523).toDF().select(round('value,2)).show()
+---------------+
|round(value, 2)|
+---------------+
|            2.0|
|           2.12|
|           3.65|
+---------------+


scala> Seq(1.9999,2.1234,3.6523).toDF().select(round('value,0)).show()
+---------------+
|round(value, 0)|
+---------------+
|            2.0|
|            2.0|
|            4.0|
+---------------+


scala> Seq(1.9999,2.1234,3.6523).toDF().select(round('value)).show()
+---------------+
|round(value, 0)|
+---------------+
|            2.0|
|            2.0|
|            4.0|
+---------------+

scala> Seq(1.9999,2.1234,3.6523).toDF().select('value.cast("int")).show()
+-----+
|value|
+-----+
|    1|
|    2|
|    3|
+-----+

【讨论】:

    【解决方案2】:

    您不需要强制转换列。如果你想去掉小数点后的数字,你可以使用round(colName, 0)

    【讨论】:

    • 四舍五入
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多