当前位置: 首页 > article >正文

js常用方法之: 加减乘除运算

方法:

// 运算
// num1: 第一个数, num2: 第二个数, symbol: 符号(+-*/)
amend: function(num1, num2, symbol) {
	if (!num1) num1 = 0;
	if (!num2) num2 = 0;
	var str1 = num1.toString(),
		str2 = num2.toString(),
		result, str1Length, str2Length
	//解决整数没有小数点方法
	try {
		str1Length = str1.split('.')[1].length
	} catch (error) {
		str1Length = 0
	}
	try {
		str2Length = str2.split('.')[1].length
	} catch (error) {
		str2Length = 0
	}
	var step = Math.pow(10, Math.max(str1Length, str2Length))
	switch (symbol) {
		case "+":
			result = (num1 * step + num2 * step) / step
			break;
		case "-":
			result = (num1 * step - num2 * step) / step
			break;
		case "*":
			result = ((num1 * step) * (num2 * step)) / step / step
			break;
		case "/":
			result = (num1 * step) / (num2 * step)
			break;
		default:
			break;
	}
	return result
},

调用:

amend(5, 1, '-'); //输出为4


http://www.kler.cn/a/444229.html

相关文章:

  • 联合索引的使用
  • YOLOv8目标检测——详细记录使用ONNX Runtime进行推理部署C++/Python实现
  • elasticsearch 7.6.2版本即使使用wildcard模糊查询,也毫无过滤效果分析
  • 实操给桌面机器人加上超拟人音色
  • 【21天学习AI底层概念】day8 适合新手免费训练 AI 模型的网站和平台
  • Redis篇-15--数据结构篇7--Sorted Set内存模型(有序集合,跳跃表skip list,压缩列表ziplist)
  • 使用VLC 搭建 RTSP 服务器
  • 监控易平台:提升IDC 数据中心运维效率与质量
  • RestTemplate实时接收Chunked编码传输的HTTP Response
  • GPT-Omni 与 Mini-Omni2:创新与性能的结合
  • 宝塔SSL证书申请失败,报错:申请SSL证书错误 module ‘OpenSSL.crypto‘ has no attribute ‘sign‘(已解决)
  • 探秘数据库索引:功能、意义与实例
  • C++ 的 format 和 vformat 函数
  • 源码安装PHP-7.2.19
  • HCIA-Access V2.5_4_3_VLAN间路由
  • 射频测试入门学习(三)——程控仪器是怎样和电脑连接通信的
  • Electron-Vue 开发下 dev/prod/webpack server各种路径设置汇总
  • 在ESP32使用AT指令集与服务器进行TCP/IP通信时,<link ID> 解释
  • ref 和 reactive 你觉得在项目中使用那个更合适
  • 5G 车联网赋能消防车调度,推动高效智能消防救援