04-09-2021 07:09
- Mark as New
- Bookmark
- Subscribe
- Permalink
- Report this post

04-09-2021 07:09
- Mark as New
- Bookmark
- Subscribe
- Permalink
- Report this post
Hello, I would like to limit a decimal number, with a number of decimal digits preset by me (2 would be fine), there is a funcion to do this?
Answered! Go to the Best Answer.

- Labels:
-
JavaScript
Accepted Solutions
04-09-2021 13:54
- Mark as New
- Bookmark
- Subscribe
- Permalink
- Report this post


04-09-2021 13:54
- Mark as New
- Bookmark
- Subscribe
- Permalink
- Report this post
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
Gondwana Software

04-09-2021 13:54
- Mark as New
- Bookmark
- Subscribe
- Permalink
- Report this post


04-09-2021 13:54
- Mark as New
- Bookmark
- Subscribe
- Permalink
- Report this post
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
Gondwana Software

04-09-2021 15:00
- Mark as New
- Bookmark
- Subscribe
- Permalink
- Report this post

04-09-2021 15:00
- Mark as New
- Bookmark
- Subscribe
- Permalink
- Report this post
keep giving me Nan as the value of the label... How could I fix it?

04-09-2021 15:12
- Mark as New
- Bookmark
- Subscribe
- Permalink
- Report this post

04-09-2021 15:12
- Mark as New
- Bookmark
- Subscribe
- Permalink
- Report this post
var bar = new Barometer();
bar.onreading = () => {
txtpressure.text = Math.round(bar.pressure / 100);
}
bar.start();
appoggio = (txtpressure/1013).toFixed(2);
console.log(appoggio);
It's appoggio that has a problem...

04-09-2021 15:19
- Mark as New
- Bookmark
- Subscribe
- Permalink
- Report this post


04-09-2021 15:19
- Mark as New
- Bookmark
- Subscribe
- Permalink
- Report this post
I'm guessing that txtpressure isn't a number, but is a <text> object.
Gondwana Software

04-09-2021 15:32
- Mark as New
- Bookmark
- Subscribe
- Permalink
- Report this post

04-09-2021 15:32
- Mark as New
- Bookmark
- Subscribe
- Permalink
- Report this post
- Who Voted for this post?
thank you very much @Gondwana, sorry fot the disturb.
08-12-2022 00:55
- Mark as New
- Bookmark
- Subscribe
- Permalink
- Report this post

08-12-2022 00:55
- Mark as New
- Bookmark
- Subscribe
- Permalink
- Report this post
It seems like Math.round() is a better solution, but it is not! In some cases it will NOT round correctly. Also, toFixed() will NOT round correctly in some cases.
To correct the rounding problem with the previous Math.round() and toFixed(), you can define a custom JavaScript round function that performs a "nearly equal" test to determine whether a fractional value is sufficiently close to a midpoint value to be subject to midpoint rounding. The following function return the value of the given number rounded to the nearest integer accurately.
Number.prototype.roundTo = function(decimal) {
return +(Math.round(this + "e+" + decimal) + "e-" + decimal);
}
var num = 9.7654;
console.log( num.roundTo(2)); //output 9.77

