Skip to content

截尾取整 | Math #14

Open
Open

Description

@haozi

Activity

  1. benboba commented on Oct 30, 2020

    @benboba

    直接减去自身的模会遇到浮点数精度问题
    1.13 - 0.13 = 0.9999999999999999

    所以不能直接返回 int,需要一个修补函数,类似这样的:
    const fixedFloat = x => {
    const [int, decimal] = x.toString().split('.')
    if (!decimal) return x;
    if (decimal[0] === '0') return +int; // 此处可能遇到另一个坑,就是科学计数法,但如果只是为 trunc 服务,应该是可以的
    return +int + 1;
    };

  2. haozi commented on Oct 30, 2020

    @haozi
    CollaboratorAuthor

    @benboba
    直接减去自身的模会遇到浮点数精度问题
    1.13 - 0.13 = 0.9999999999999999

    所以不能直接返回 int,需要一个修补函数,类似这样的:
    const fixedFloat = x => {
    const [int, decimal] = x.toString().split('.')
    if (!decimal) return x;
    if (decimal[0] === '0') return +int; // 此处可能遇到另一个坑,就是科学计数法,但如果只是为 trunc 服务,应该是可以的
    return +int + 1;
    };

    不过,话说回来,如果用 toString 的话,直接就可以用字符串的方法 trunc 了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions