在 Julia Lang 中将 float 转换为 int

问题描述 投票:0回答:8

Julia 有没有办法将浮点数转换为 int ?我正在尝试将浮点数转换为固定精度数,小数部分表示为 8 位整数。为了做到这一点,我需要截断数字的小数部分,我认为最好的方法是从浮点 x 中减去转换后的 x 整数:

  x = 1.23455
y = x - Int(x)
println(y)

y = 0.23455

floating-point int julia
8个回答
44
投票

您可能正在寻找

trunc
。这取决于小数部分的含义。这就是
trunc
floor
之间的区别:

julia> trunc(Int, 1.2)
1

julia> trunc(Int, -1.2)
-1

julia> floor(Int, 1.2)
1

julia> floor(Int, -1.2)
-2

14
投票

我认为您正在寻找

floor

julia> x = 1.23455
1.23455

julia> floor(x)
1.0

julia> y = x - floor(x)
0.23455000000000004

5
投票

结合之前的答案:

julia> int(x) = floor(Int, x)
int (generic function with 1 method)

julia> int(3.14)
3

julia> int(3.94)
3

5
投票

要回答标题中的一般问题(将 Float 转换为 Int),我们可以这样做:

round(Int, 1.3)
# 1
round(Int, 1.7)
# 2

3
投票

根据

floor
文档 你可以这样做

julia> x = 45.5
45.5

julia> typeof(x)
Float64

julia> x = floor(Int8,x)
45

julia> typeof(x)
Int8

2
投票

看来你真正需要的是数字的小数部分。如果是这种情况,您可以直接使用模 1,如下所示:

x = 1.23455
y = x % 1
println(y)
# 0.2345

1
投票

看来你真的需要

modf
来代替:

help?> modf
search: modf ComposedFunction mod1 mod module

  modf(x)

  Return a tuple (fpart, ipart) of the
  fractional and integral parts of a number.      
  Both parts have the same sign as the argument.  

  Examples
  ≡≡≡≡≡≡≡≡≡≡

  julia> modf(3.5)
  (0.5, 3.0)
  
  julia> modf(-3.5)
  (-0.5, -3.0)


0
投票

如果要将 Float 转换为 Int,这是一个两步操作。因为在类型转换之前必须截断小数部分:

i = Int(trunc(1.23455))

否则,您可以使用

modf
将浮点数拆分为包含两个浮点数的元组,这两个浮点数保存原始数字的整数部分和小数部分。

(i, p) = modf(1.23455)
© www.soinside.com 2019 - 2024. All rights reserved.