当前位置:网站首页>Precision problems and solutions of JS decimal conversion percentage
Precision problems and solutions of JS decimal conversion percentage
2022-07-21 20:48:00 【Fan Xiaoduo】
because JS Its own mechanism , If you multiply by 100+% String splicing will cause accuracy problems
for example :
(0.359*100)% -> 3.5900000000000003%
Solution 1 :
parseFloat((num * 100).toPrecision(12))+"%" // toPrecision Format the number to the specified length
Solution 2 :
// num Is the target number ,n Is the accuracy ( Keep a few decimal places )
function formatFloat (num, n=2) {
let f = parseFloat(num);
if (isNaN(f)) return false;
f = Math.round(num * Math.pow(10, n)) / Math.pow(10, n); // floor House round rounding ceil Enter into
let s = f.toString();
let rs = s.indexOf('.');
// Determine if it is an integer , Add the decimal point and fill in 0
if (rs < 0) {
rs = s.length;
s += '.';
}
while (s.length <= rs + n) {
s += '0';
}
return s;
}
formatFloat(0.359*100)% -> 3.59%
边栏推荐
- 图片横向瀑布流
- Lazy loading of pictures
- Web server / client setup (nodejs starts exe program)
- Flutter error record: navigator dart‘: Failed assertion: line 4041 pos 12: ‘!_ debugLocked‘: is not true.
- swift 导航栏颜色设备和去掉下边缘线
- First Working Day~
- Usage and introduction of sonarlint
- thinkphp5.1 利用 PHPMailer 发送邮件
- PHP date() 函数
- The text file is transferred to the external server through the web proxy server and returned after modification
猜你喜欢
First Working Day~
18. [precautions for pointer pointing to two-dimensional array]
DVWA[SQL-Injection]报错注入学习记录
Openfoam programming: combination of VOF method and porous media model
Porous media in openfoam
10. [file opening format and its determination of whether to open]
20. [char* is equal to string but not equal]
Solve the problem that Safari browser blocks window open
thinkphp6使用EasyWeChat5.x公众号开发(二)
使用tailwind在谷歌浏览器上,button会出现蓝色背景的问题
随机推荐
First Working Day~
Differences and usage scenarios between usememo and usecallback
JS operation mechanism
thinkphp6使用EasyWeChat5.x公众号开发(二)
Difference between controlled and uncontrolled components
thinkphp5.1下使用 jwt 进行验证
Koa2快速搭建服务器
Mise en œuvre personnalisée du cadre MVC
xcode升级后找不到 C语言头文件 stdio.h的解决办法
移动安全入门指南
Swift navigation bar color device and remove the lower edge line
Openfoam programming: combination of VOF method and porous media model
宽字节注入学习记录
Porous media in openfoam
Add, delete, modify and check~
12. [i/o flow get() and getline() and put() functions]
线性薛定谔方程实现界面推移
Reset Form
nodejs使用POST方法接收js对象并写入json文件
大文件下载 解决方案