﻿ 在JavaScript中判断整型的N种方法 | ZeroBox Notes

在JavaScript中判断整型的N种方法

ECMAScript 5

function isInteger(x) {
return x % 1 === 0;
}

> isInteger(17)
true
> isInteger(17.13)
false

> 3.5 % 1
0.5
> -3.5 % 1
-0.5

> isInteger('')
true
> isInteger('33')
true
> isInteger(false)
true
> isInteger(true)
true

function isInteger(x) {
return (typeof x === 'number') && (x % 1 === 0);
}

function isInteger(x) {
return Math.round(x) === x;
}

> isInteger(17)
true
> isInteger(17.13)
false

> isInteger('')
false

function isInteger(x) {
return (x | 0) === x;
}

> isInteger(Math.pow(2, 32))
false

parseInt()也提供了跟Math.round()类似将数字转换成整型的方法。

function isInteger(x) {
return parseInt(x, 10) === x;
}

> isInteger(1000000000000000000000)
false

> parseInt(1000000000000000000000, 10)
1
> String(1000000000000000000000)
'1e+21'

ECMAScript 6

> Math.trunc(4.1)
4
> Math.trunc(4.9)
4
> Math.trunc(-4.1)
-4
> Math.trunc(-4.9)
-4
{"ft_lang_label":"__label__zh","ft_lang_prob":0.89940536,"math_prob":0.9985221,"size":1883,"snap":"2019-43-2019-47","text_gpt3_token_len":1101,"char_repetition_ratio":0.19425227,"word_repetition_ratio":0.027210884,"special_character_ratio":0.32342008,"punctuation_ratio":0.14963503,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.99742484,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2019-10-24T04:09:04Z\",\"WARC-Record-ID\":\"<urn:uuid:3adea4b3-0d6a-4fcd-a459-115d12e4e511>\",\"Content-Length\":\"13718\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:3f3070a6-18ec-48d9-a5a4-8dec059ef2fe>\",\"WARC-Concurrent-To\":\"<urn:uuid:b51a8dc8-3e5d-4a51-883b-93fec22eda11>\",\"WARC-IP-Address\":\"61.188.39.61\",\"WARC-Target-URI\":\"http://zerobox.org/notes/916.html\",\"WARC-Payload-Digest\":\"sha1:55NATPGNGZL5WN33WFZQQR675S7I7U3C\",\"WARC-Block-Digest\":\"sha1:T2JZUFZU3CEPAB26EJU53I5TB6L5OGZ5\",\"WARC-Identified-Payload-Type\":\"application/xhtml+xml\",\"warc_filename\":\"/cc_download/warc_2019/CC-MAIN-2019-43/CC-MAIN-2019-43_segments_1570987841291.79_warc_CC-MAIN-20191024040131-20191024063631-00064.warc.gz\"}"}