Google Apps Script中如何将float数值转换为integer或文本
Google Apps Script 浮点数转整数/文本格式实现方案
调用天气接口解析JSON返回值时,cloudcover字段默认被解析为浮点数,直接打印会输出9.0这类带.0后缀的结果,对应测试代码如下:
function test(){ const url = "https://www.7timer.info/bin/astro.php?lon=113.2&lat=23.1&ac=0&unit=metric&output=json&tzshift=0"; const res = UrlFetchApp.fetch(url); const data = JSON.parse(res.getContentText()); var cloud = data.dataseries[0].cloudcover; Logger.log(cloud); // 打印结果为 9.0 }
转换为Integer整数类型
可根据场景选择以下任意一种方式,均能将9.0类浮点数转为整数9:
Math.round()四舍五入取整,兼容字段可能出现非.0小数的场景:const cloudInt = Math.round(cloud); Logger.log(cloudInt); // 输出 9parseInt()直接舍弃小数部分取整:const cloudInt = parseInt(cloud); Logger.log(cloudInt); // 输出 9- 双非位运算取整,仅适用于云量这类正整数场景,执行效率更高:
const cloudInt = ~~cloud; Logger.log(cloudInt); // 输出 9
云量字段本身取值范围为0-100的整数,接口返回浮点类型是JSON解析的默认行为,以上取整方式均不会产生精度损失。
转换为文本格式
如果需要获取不带.0后缀的字符串结果,可参考以下实现:
- 先转整数再转字符串,兼容性最好:
const cloudStr = Math.round(cloud).toString(); Logger.log(cloudStr); // 输出 "9" - 正则替换末尾
.0后缀,适合明确所有返回值均为x.0格式的场景:const cloudStr = String(cloud).replace(/\.0$/, ''); Logger.log(cloudStr); // 输出 "9"
内容的提问来源于stack exchange,提问作者Amir Flax
相关产品推荐
相关产品推荐

