英文:
Best way to divide floats
问题
I'm working on a REST API that syncs client with the server's time to keep the client in sync and avoid any connection issues. I encountered this issue while dividing floats (I was doing server time (epoch) calculations):
1672866847.265 + (208420 / 1000)
results in 1672867055.6850002
(which I know is IEEE 754)
meanwhile according to Google's calculator, it should be 1672867055.69
Is there a way to solve this issue?
英文:
I'm working on a REST API that syncs client with the server's time to keep the client in sync and avoid any connection issues. I encountered this issue while dividing floats (I was doing server time (epoch) calculations):
1672866847.265 + (208420 / 1000)
results in 1672867055.6850002
(which I know is IEEE 754)
mean while according to Google's calculator, it should be 1672867055.69
Is there a way to solve this issue?
答案1
得分: 2
你可以使用 toFixed(2)
来保留两位小数:
console.log((1672866847.265 + 208420 / 1000).toFixed(2));
英文:
You can use toFixed(2)
to get 2 decimal points:
console.log((1672866847.265 + 208420 / 1000).toFixed(2));
答案2
得分: 1
If you want your result to be more reliable try first multiplying:
如果你想要结果更可靠,首先尝试将其相乘:
You can also use a library:
你也可以使用一个库:
英文:
If you want your result to be more reliable try first multiplying
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
console.log(1672866847.265 + (208420 / 1000))
console.log((1672866847.265 * 1000 + 208420) / 1000)
<!-- end snippet -->
You can also use a library
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
console.log(new Big(1672866847.265).plus(new Big(208420).div(1000)).toNumber())
<!-- language: lang-html -->
<script src='https://cdn.jsdelivr.net/npm/big.js@6.2.1/big.min.js'></script>
<!-- end snippet -->
答案3
得分: 0
你可以使用 round
来避免小数值 -
Math.round(1672867055.6850002); // 答案将是:1672867056
要获得带有两位小数点的值,您可以将其乘以100,然后除以100
Math.round(1672867055.6850002 * 100)/100; // 答案将是:1672867055.69
英文:
You can use round
to avoid decimal values -
Math.round(1672867055.6850002); // ans will be: 1672867056
To get value with two decimal point, you can mupltiply it by 100 and then divid it by 100
Math.round(1672867055.6850002 * 100)/100; // ans will be: 1672867055.69
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论