最佳的浮点数分割方法

huangapple go评论96阅读模式
英文:

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 -->

&lt;script src=&#39;https://cdn.jsdelivr.net/npm/big.js@6.2.1/big.min.js&#39;&gt;&lt;/script&gt;

<!-- 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

huangapple
  • 本文由 发表于 2023年1月5日 05:43:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75011662.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定