Fixed Length Number with Decimals as well - javascript

I have a number of variable length the looks something like this:
48.4532
I want to convert it to 4 digits before decimal and 2 decimal places, so the number above should be:
0048.45
I also don't want to show decimals unless they are necessary, so:
48
should become:
0048
I was able to get the fixed length, but I couldn't get the decimals to show up only if they were necessary (I don't want to show two 0's at the end).
This is how I got a fixed length:
trackPartLength = ("0000" + trackPartLength.toString()).slice(-4); // Convert to fixed length
How do I add the 2 decimal points only if they are needed?
Edit: I also just realized that if the number does have decimals with the above code, it moves the decimal point over 4 spots causing some other problems, so I'm not sure if my initial approach is a good one. I'm trying to right a fixed length function of variable fixed prefix and decimal length.

This should work:
trackPartLength = ("0000" + trackPartLength.toFixed(2)).slice(-7).replace( /\.00$/, '' );
It uses toFixed to get the two decimal points, zero pads and then removes any trailing .00. Examples:
48.4532 -> 0048.45
48 -> 0048
6.213 -> 0006.21
12345 -> 2345
1234.56789 -> 1234.57
If the number can have more than four digits before the decimal, as in the 12345 example, you may want to make the zero padding and slice conditional, so that you don't remove leading digits from a big number. That could be done like this:
var tmp = trackPartLength.toFixed(2);
trackPartLength = (tmp.length >= 7 ? tmp : ('0000' + tmp).slice(-7)).replace( /\.00$/, '' );

Related

Javascript replacing last number digits with 0 instead of representing the number in exponential notation

I have javascript code that's supposed to work with big numbers and expect them to be displayed in exponential notation. I can't figure out why x value has the last 4 digits replaced with 0, but y value which is even a bigger number just gets displayed as it's supposed to - with exponential notation. Then I want to display x with fixed points and it returns totally wrong value. The following code was tested in the console. Any idea why this happens?
var y=1111111111111111111111111111111111111111 > 1.1111111111111112e+39
var x=111111111111111111111 > 111111111111111110000
Number(x).toFixed(4) > "111111111111111114752.0000"
var y=1111111111111111111111111111111111111111;
console.log(y);
var x=111111111111111111111 ;
console.log(x);
console.log(Number(x).toFixed(4));
toFixed() returns a string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If the absolute value of numObj is greater or equal to 1e+21, this method simply calls Number.prototype.toString() and returns a string in exponential notation.
Warning: Floating point numbers cannot represent all decimals precisely in binary. This can lead to unexpected results, such as 0.1 + 0.2 === 0.3 returning false .
For more information check : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
I think the number does not store data to so many digits; in both cases it is same it storing 17 digits and rest is displayed as exponent part;
1.111111111111111 2e+39
11111111111111111 0000
|----------------| 17 digits
But turns out somehow the js engine decided to print x without exponent part and the 0 is due to the way big numbers are internally stored; System can only store so many digits after decimal
You can use this
Number.isSafeInteger(x) //returns boolean to check if it is safe to use it
you can read more about it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER

How do I round to 1 decimal on the bbc:microbit with javascript w/o toFixed(), the usual multiplication + divide gives trailing 9999 digits?

temperatureReading = Math.round(temperatureReading * 10) / 10
gives me 26.29999999999999999999 instead of 26.3
And 26.00000000001 instead of 26.0
I get alternating 2 values from the temperature sensor: 26.33 and 26.3200000
After the conversion I have: 26.2999999999999
The number of the repeating digits above is just an example. My display on the micro bit is not wide enough to see them all.
I use toString() to display the values.
Unfortunately, toFixed() and toPrecision() is not available on the micro:bit
Can the rounding be achieved by some other operations?
With the following code I can now get numbers with 1 decimal as a string:
let temperatureStr = Math.round(temperatureReading * 10).toString()
let temperature = temperatureStr.slice(0, temperatureStr.length - 1) + "." + temperatureStr.slice(temperatureStr.length - 1);
I first multiply the number by 10 and convert the result to a string. Then, I insert the decimal point before the last digit. This gives me the string I want to print.

How can I parse a string as an integer and keep decimal places if they are zeros?

I have these strings: "59.50" & "30.00"
What I need to do is convert them to integers but keep the trailing zeros at the end to effectively return:
59.50
30.00
I've tried:
Math.round(59.50 * 1000) / 1000
Math.round(30.00 * 1000) / 1000
but ended up with
59.5
30
I'm assuming I need to use a different method than Math.round as this automatically chops off trailing zeros.
I need to keep these as integers as they need to be multiplied with other integers and keep two decimals points. T thought this would be fairly straight forward but after a lot of searching I can't seem to find a solution to exactly what I need.
Thanks!
Your premise is flawed. If you parse a number, you are converting it to its numerical representation, which by definition doesn't have trailing zeros.
A further flaw is that you seem to think you can multiply two numbers together and keep the same number of decimal places as the original numbers. That barely makes sense.
It sounds like this might be an XY Problem, and what you really want to do is just have two decimal places in your result.
If so, you can use .toFixed() for this:
var num = parseFloat("59.50");
var num2 = parseFloat("12.33");
var num3 = num * num2
console.log(num3.toFixed(2)); // 733.64
Whenever you want to display the value of the variable, use Number.prototype.toFixed(). This function takes one argument: the number of decimal places to keep. It returns a string, so do it right before viewing the value to the user.
console.log((123.4567).toFixed(2)); // logs "123.46" (rounded)
To keep the decimals - multiply the string by 1
example : "33.01" * 1 // equals to 33.01
Seems you are trying to retain the same floating point, so better solution will be some thing like
parseFloat(string).toFixed(string.split('.')[1].length);
If you want numbers with decimal points, you are not talking about integers (which are whole numbers) but floating point numbers.
In Javascript all numbers are represented as floating point numbers.
You don't need the trailing zeros to do calculations. As long as you've got all the significant digits, you're fine.
If you want to output your result with a given number of decimal values, you can use the toFixed method to transform your number into a formatted string:
var num = 1.5
var output = num.toFixed(2) // '1.50'
// the number is rounded
num = 1.234
output = num.toFixed(2) // '1.23'
num = 1.567
output = num.toFixed(2) // '1.57'
Here's a more detailed description of toFixed: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

Converting roman numbers to integers

I want to replace certain strings (roman numbers) in a string with nodejs.
A simple concatenation of .replace() is not working as expected, because obviously some roman numbers are contained with other roman numbers. That sounds awful, but this example explains:
"III".replace('I', '1');
// "111";
offcourse we can reorder the .replace() methods to surpress this behaviour, like so:
"III".replace('III', '3').replace('II', '2').replace('I', '1');
// "3"
But then with XI we get into trouble.
Is there a smarter way to do this?
Of course. You have to add the numbers. For example:
"111" could be 1+1+1 = 3
You have to be sure that sometimes an small number on the left of a bigger number should substract in the final number. So if you validate that it's really easy.
For example:
"IV" = 4
I = 1
V = 5
I<V
So, the result will be:
5-1 = 4
The number 1 should be substracted because is on the left of a bigger number.

Remove last digits from an int

Can't seem to find a good answer to this question. How do I remove the last 11 digits from an int?
The id could be one or more numbers in the beginning but there will always be 11 digits following the id. There will always be an id in the beginning. {id}{11 digits}.
var getId = function (digits) {
// Do some stuff and return id
}
getId(110000000001); // Should return 1
getId(1110000000001); // Should return 11
getId(2010000000001); // Should return 20
Divide by 1e11 and take the floor:
var stripped = Math.floor(id / 1e11);
This avoids conversion to/from a string representation.
Note that the nature of JavaScript numerics is such that your "raw" values (the values with the 11 useless digits) can't have more than 5 digits in addition to those 11 before you'll start running into precision problems. I guess if you never care about the low-order 11 digits that might not be a problem.
Try this:
var str = 1100000000011;
var res = str.toString().substr(0, str.toString().length - 11);
Demo
You can convert your number to string and delete tailing digits:
digits.toString().replace(/\d{11}$/, '')
By the way, you better don't use ints (or to be precise, Numbers) because if number is greater than 2147483648 (by absolute value), it'll be represented internally as double resulting in precision loss. If don't need tailing digits, then it's okay — use division approach suggested in other answers (this one could break because of scientific notation). But if you want to keep all the data, you should represent your numbers with strings.
You can use division and 10^11 to do so.
Edit: my bad
var getId = function (digits) {
var id = parseInt((digits/(1e11)),0);
}
You can convert the number to a string and slice the last 11 characters from the end
parseInt( digits.toString().slice(0, -11) );
Using .slice( 0 , [ negative_number ]); will slice x characters from the end of the string
More information on .slice() Here

Categories

Resources