Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not use Number.toFixed for Rounding #809

Open
tomoyukikashiro opened this issue Aug 1, 2022 · 0 comments
Open

Do not use Number.toFixed for Rounding #809

tomoyukikashiro opened this issue Aug 1, 2022 · 0 comments

Comments

@tomoyukikashiro
Copy link
Owner


date: 2018-11-18
title: Do not use Number.toFixed for Rounding
slug: do-not-use-number-tofixed-for-rounding
lang: en-US
tags: [javascript]

Sometimes I saw Use-case that developer use Number.prototype.toFixed for rounding.
But It is not correct in some reasons. I try to explain why it's not correct. 😥

Return String instead of Number/Float

The result of toFixed is String so it case unexpected result if you calculate.

// What you expect// 1.1 + 1 = 2.1
// Result1.12.toFixed(1) + 1// '1.1' + 1 = '1.11'

Not accurate in one case

You can pass digits option to toFixed([digits]) it means ...

digits

Optional. The number of digits to appear after the decimal point; this may be a value between 0 and 20, inclusive, and implementations may optionally support a larger range of values. If this argument is omitted, it is treated as 0.

For example you run 1.1N.toFixd(1) the return value would be 1.N.Okay let's see what's happened in real world example.

1.150.toFixed(1) // -> '1.1' expected '1.2' because of rounding
1.15.toFixed(1)  // -> '1.1' expected '1.2' because of rounding
1.151.toFixed(1) // -> '1.2'

To rounding the number which next to digits should be greater than 0. 💩

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant