Converting number into string in JavaScripts without trailing zeros from number - javascript

I tried to convert number to string in JavaScripts using toString() but it truncates insignificant zeros from numbers. For examples;
var n1 = 250.00
var n2 = 599.0
var n3 = 056.0
n1.toString() // yields 250
n2.toString() // yields 599
n3.toString() // yields 56
but I dont want to truncate these insignificant zeros ( "250.00"). Could you please provide any suggestions?. Thank you for help.

The number doesn't know how many trailing 0 there are because they are not stored. In math, 250, 250.00 or 250.0000000000000 are all the same number and are all represented the same way in memory.
So in short, there is no way to do what you want. What you can do is format all numbers in a specific way. See Formatting a number with exactly two decimals in JavaScript.

As far as I know, you can't store number with floating zeros, but you can create zeroes with floating zeroes, by using toFixed:
var n1 = 250;
var floatedN1 = n1.toFixed(2); //type 'string' value '250.00'

Related

How to convert a decimal (base 10) to 32-bit unsigned integer?

How to convert a decimal (base 10) to 32-bit unsigned integer?
Example:
If n = 9 (base 10), how to convert it to something like: 00000000000000000000000000001001 (base 2)?
Let's be clear that when you're talking about number bases, you're talking about textual representations (which code will see as strings). Numbers don't have number bases, they're just numbers (but more on this below). A number base is a way of representing a number with a series of digits (text). So n = 9 isn't base 10 or base 36 or base 2, it's just a number. (The number literal is in base 10, but the resulting number has no concept of that.)
You have a couple of options:
Built in methods
The number type's toString accepts a radix (base) to use, valid values are 2 through 36. And the string padStart method lets you pad the start of a string so the string is the desired number of characters, specifying the padding character. So:
const n = 9;
const binaryText = n.toString(2).padStart(32, "0");
console.log(binaryText);
If your starting point is text (e.g., "9" rather than 9), you'd parse that first. My answer here has a full rundown of your number parsing options, but for instance:
const decimalText = "9";
const binaryText = (+decimalText).toString(2).padStart(32, "0");
console.log(binaryText);
Bit manipulation
"Numbers don't have number bases, they're just numbers" is true in the abstract, but at the bits-in-memory level, the bits are naturally assigned meaning. In fact, JavaScript's number type is an implementation of IEEE-754 double-precision binary floating point.
That wouldn't help us except that JavaScript's bitwise & and | operators are defined in terms of 32-bit binary integers (even though numbers aren't 32-bit binary integers, they're 64-bit floating point). that means we could also implement the above by testing bits using &:
const n = 9;
let binaryText = "";
for (let bit = 1; bit < 65536; bit *= 2) {
binaryText = (n & bit ? "1" : "0") + binaryText;
}
console.log(binaryText);
Hoping u guys have already practiced javascript in leetcode using andygala playlists
function flippingBits(n){
n = n.toString(2).padStart(32, "0");
n=(n.split(''))
for(let i=0;i<32;i++){
(n[i]==='1')? n[i]='0': n[i]='1';
}
n=n.join('')
let n=parseInt(n,2)
return n;
}
console.log(flippingBits(9))

Does the number -0 exists in Javascript?

I was doing some money calculation and I got the number -0. This number -0 does not exists, since 0 does not have a sign. Why is this happening? I know the original price has more digits on my bd. but anyway this behaviour thing is weird anyway.
So I'm using this math expression: I pick the item price and subtract the discount, then I round it up.
(19.99923-20).toFixed(2)
And I get "-0.00" !? this is ugly to display. I tried using the Number() to make it a "real number", but
Number((19.99923-20).toFixed(1))
will appear as "-0".
What's wrong with javascript, there is no number -0, it should be just "0"?
JavaScript keeps sign with floating negatives close to 0, either using Math.round() or toFixed(), both can get you a -0. Solved that applying a quick fix, which consists in checking if our number enters that range in between 0 and -0.005 (rounded to -0.01 later). Considered 2 floating digits as your example works with money, so I considered a difference of 1 cent relevant:
var num=19.99923-20;
if(num>-0.005 && num<0){
num=0; //we set to '0' all -0
}else{
num=num*100;
num=Math.round(num);
num=num/100;
/*or
num=num.toFixed(2);
but this way we convert number to string*/
}
Hope it helps.
toFixed converts a number to string, not a number. So the -0.00 you are seeing is a string. Its the result of converting
19.99923-20 // which is about
-0.0007699999999992713 // in internal representation
to a string using the toFixed method in ECMAscript standards, which initialises the result to "-" for negative numbers and proceeds to convert the absolute (positive) value of the number being converted.
Converting the string "-0.00" back to a number with either parseFloat("-0.00") or Number("-0.00") returns a positive zero number representation (javscript stores numbers using the IEEE 754 standard for double precision float representation, which does have a negative zero value, but it's not the problem here.)
Looking at how toFixed works suggests the only problem is with a "-0.00" result, which can be checked using string comparison:
var number = 19.99923-20;
var str = number.toFixed(2);
if( str == "-0.00")
str = "0.00";
Alternatively you could consider using a conversion routine which never returns a negatively signed zero string such as:
function convertFixed( number, digits) {
if(isNaN(number))
return "NaN";
var neg = number < 0;
if( neg)
number = -number;
var string = number.toFixed(digits);
if( neg && Number(string) === 0) // negative zero result
neg = false;
return neg ? "-" + string : string;
}

What is number and how to convert?

I have custom calculator with js, everything was normal until i found 1.2101997764095421e-12 sometimes X.XXe-13, X.XXe-14
What is this ? How to convert it ?
Update :
I have knowledge in excel for this calculator, the result for 1.2101997764095421e-12 should be a 14,78
Those are really long floating point number, and the e-12 represents that there are 12 decimals. To convert it to your desired format you can do this:
var converted = Math.round(number * 100) / 100
This is nothing specific to javascript but a common mathematical notation meaning the following:
1e-1 = 0.1
1e-2 = 0.01
x.xxe-13 points to a number having 13 decimals after 0.
This is a representation of Scientific Notation. You can translate the eN to mean x10^N. When a Float number gets to large or small the string representation number will look that way.
1.12345e5 = 1.12345x10^5 = 112345
1.12345e-5 = 1.12345x10^-5 = .0000112345

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

Is this a valid way to truncate a number?

I found this code in a SO answer as a way to truncate a number into an integer in Javascript:
var num = -20.536;
var result = num | 0;
//result = -20
Is this a valid way to truncate a number in Javascript, or it is some kind of hack? Why does it works only with numbers less than 2147483647?
That method works by implicitly converting the number to a 32-bit integer, as binary operators use 32-bit integers in their calculations.
The drawbacks of that method are:
The desired operation is hidden as an implicit effect of the operator, so it's not easy to see what the intention of the code is.
It can only handle integers within the range of a 32-bit number.
For any regular case you should use the Math.floor or Math.ceil methods instead, it clearly shows what the intention of the code is, and it handles any number within the precision range of a double, i.e. integers up to 52 bits:
var num = 20.536;
var result = Math.floor(num); // 20
var num = -20.536;
var result = Math.ceil(num); // -20
There is no round-towards-zero method in Javascript, so to do that you would need to check the sign before rounding:
var result = num < 0 ? Math.ceil(num) : Math.floor(num);
Use Javascript's parseInt like so:
var num = -20.536;
var num2int = parseInt(num);
return num2int; //returns -20
Tada! num is now an int with the value of -20.
If you use parseInt you can go from -2^53 to +2^53:
parseInt(-20.536) // -20
parseInt(9007199254740992.1234) // 9007199254740992
Why +/- 2^53? This is because JavaScript uses a 64-bit representation for floating point numbers, with a 52-bit mantissa. Hence all integer values up to 2^53 can be represented exactly. Beyond this, whole numbers are approximated.

Categories

Resources