WeStudio技术社区

 找回密码
 立即注册

快捷登录

QQ登录

只需一步,快速开始

查看: 625|回复: 0

如何把科学计数法转换为十进制表示?

[复制链接]

99

主题

142

帖子

1046

积分

版主

Rank: 7Rank: 7Rank: 7

积分
1046
发表于 2022-7-12 17:28:36 | 显示全部楼层 |阅读模式
本帖最后由 hixon 于 2022-7-12 17:34 编辑

将下面的转换方法放到全局代码(init.js)中定义
  1. var scientificToDecimal = function (num) {
  2.     var nsign = num/Math.abs(num);
  3.     //remove the sign
  4.     num = Math.abs(num);
  5.     //if the number is in scientific notation remove it
  6.     if (/\d+\.?\d*e[\+\-]*\d+/i.test(num)) {
  7.         var zero = '0',
  8.                 parts = String(num).toLowerCase().split('e'), //split into coeff and exponent
  9.                 e = parts.pop(), //store the exponential part
  10.                 l = Math.abs(e), //get the number of zeros
  11.                 sign = e / l,
  12.                 coeff_array = parts[0].split('.');
  13.         if (sign === -1) {
  14.             l = l - coeff_array[0].length;
  15.             if (l < 0) {
  16.               num = coeff_array[0].slice(0, l) + '.' + coeff_array[0].slice(l) + (coeff_array.length === 2 ? coeff_array[1] : '');
  17.             }
  18.             else {
  19.               num = zero + '.' + new Array(l + 1).join(zero) + coeff_array.join('');
  20.             }
  21.         }
  22.         else {
  23.             var dec = coeff_array[1];
  24.             if (dec)
  25.                 l = l - dec.length;
  26.             if (l < 0) {
  27.               num = coeff_array[0] + dec.slice(0, l) + '.' + dec.slice(l);
  28.             } else {
  29.               num = coeff_array.join('') + new Array(l + 1).join(zero);
  30.             }
  31.         }
  32.     }

  33.     return nsign < 0 ? '-'+num : num;
  34. };
复制代码

在按钮的onRelease事件方法中进行测试
  1. ui.main.textButton.onRelease = function() {
  2.     util.console.log(scientificToDecimal(2.5e25));
  3.     util.console.log(scientificToDecimal('1.2e-2'));
  4.     util.console.log(scientificToDecimal('-1.123e-10'));
  5.     util.console.log(scientificToDecimal(-1e-3));
  6.     util.console.log(scientificToDecimal(12.12));
  7.     util.console.log(scientificToDecimal('0'));
  8. };
复制代码

测试结果:
scientific_to_decimal.png




回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|物一世(北京)科技有限公司 ( 京ICP备20025895 )

GMT+8, 2024-3-29 01:52 , Processed in 0.012176 second(s), 21 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表