JSON.stringify () error in javascript - javascript

I have the following code
var number = 0618260587
JSON.stringify(number)
the stringified result is 618260587 , the first zero is automatically truncated.
I tried the following fix
if(number.length<8)
{
var book1 = "0" + number;
alert(book1);
but it alerts undefined. I am not sure
1) Why the stringified data truncates the first zero
2) I thought javascript adds two variables irrespective of type

Leading zeroes are a display thing, and not normally part of numbers. There's an infinite number of invisible zeroes before/after every number, but they're not normally shown. If you want the leading zero, treat the number as a string:
var number = '0618260587';
As well, in most, numbers with a leading zero are treated as octal, not decimal. Bare leading zeroes can cause hard-to-track bugs because of this - it looks like a decimal to you, but it's some completely different number to the interpreters, eg..
0618260587 octal = 1616431 decimal

Related

Check if no unicode character is associated with a number Javascript

I am making a base converter that can convert any number in any base to the same number in any other base. Since the bases could be any number the result could have digits that represent a number greater than 10. In order to have only one character correspond to each digit in the final result, I plan to assign Unicode characters to each digit corresponding to a value greater than 10 by using String.fromCharCode(Base 10 number digit represents). However, I noticed that there was a problem with this method; It seems as if a lot of the values are blank when outputted onto the HTML webpage or only output an empty box that looks like this: ⯣. When I tried to see if the value of the Unicode character equaled the empty box or an empty string by using an if statement, it always seemed to return false, even when the Unicode character associated with the digit returned the same empty box. Please may you help me understand why this is, and how I can construct the if statement such that it will work like I want it to?
You could try this:
function convertToDecimal(num, base) {
return window.parseInt(num.toString(), base);
}
const binary = 10;
const base = 2;
console.log("Decimal version:", convertToDecimal(binary, base))

Why do trailing and leading zeros cause my function to return values i do not want?

This set of code i am providing should take any number i enter and reverse it. Currently the function works when n = 21.365 or n = 5698 but when n = 0456456456 it returns 41422397 instead of 6546546540 or when n = 056985 it returns 58965 instead of 589650 and when n = 016540 it returns 257 instead of 45610.
This is what i have written so far
//rules & limitations
//negative numbers should remain negative
//leading zeros should be removed
//the function can accept floats or integers
//the function will return integers as integers
function reverseNumberWithBuiltInFunctions(n) {
return (
parseFloat (
n
//convert the number to a string
.toString()
//convert to array of characters
.split('')
//reverse array of characters
.reverse()
//join reversed array of characters
.join('')
) * Math.sign(n)
)
}
I would like if n = 001 then 100 is returned or if n = 0456456456 then 6546546540 is returned. Essentially i am having trouble when leading or trailing zeros or both are included in "n" or it seems like issues arise when there is some sort of pattern to the numbers.
Also, why is it that when n = 016540 it returns 257?
Do you know of any solutions that could help improve the logic of the function with the given rules and limitations that would yield the desired results?
What you want is impossible if the inputs are integers or floats. There is no such thing as "leading zeros" on either integers or floats. If you use leading zeros to make a integer literal, it becomes an octal literal (changing the value; that's why n = 0456456456 behaves the way it does, 0456456456 is just the octal way to spell 79322414). If you parse a string with leading zeros to make an integer, they're simply ignored (parseInt('000123') produces the same value as parseInt('123'), namely, the value 123). That's why 016540 becomes 257: the octal literal is equivalent to the decimal literal 7520, and reversing it and parsing back to integer ignores the leading 0, leaving 257.
You can't preserve such leading zeros because they don't exist outside of string form. And you'll lose the trailing zeros on reversal because they become leading zeros in the new form.
Either work with strings exclusively, or accept that you'll lose leading zeros.
I'll note that your own rules in the comments specify:
//leading zeros should be removed
so it's working as expected here.
You have to pass it in as a string as leading 0's in your numbers will not be interpreted as such.
For example:
// Will always be evaluated as 1
let foo = 001;
console.log(foo);
If you were to supply n as a string, you may do it like this:
reverseNumberWithBuiltInFunctions = n => parseFloat(n.toString().split('').reverse().join(''));
console.log(reverseNumberWithBuiltInFunctions('0456456456'))
console.log(reverseNumberWithBuiltInFunctions('056985'))

How to get digits from a BigInt in javascript?

I am working on problem n°104 of project Euler Problem 104 and would like to do it in javascript.
In order to solve this problem I need to compute large values of the Fibonacci sequence, but the numbers produced by this sequence are too large to be handle by classic Number, so I'm using BigInt supported in the latest versions of javascript.
Once I've got a particular result stored in a BigInt, I need to check it's 10 first, and last digits.
To get the digits from a Number we usually do something like in the code below, but when the number becomes very large, things go wrong:
let number = BigInt(123456789)
console.log(number.toString())
console.log(number.toString()[3]) // Result is fine
let bigNumber = BigInt(1234567891111111111111111111111111111)
console.log(bigNumber.toString())
console.log(bigNumber.toString()[30]) // unpredictable result
It seems like the "toString()" methods is only using the precision of the Number type (2^53 I believe), thus we are quickly losing precision on the last digits of the BigInt number. The problem is I can't find other methods to extract those digits.
Edit :
I need the precision to be perfect because basicaly what i'm doing for example is :
Compute Fibonacci(500) = 280571172992510140037611932413038677189525
Get the 10 last digits of this number : 8677189525 (this is where is lose the precision)
And then to solve my problem I need to check that those 10 last digits contains all the digits from 1 to 9
For big numbers, I think you should add the n suffix:
let number = BigInt(123456789)
console.log(number.toString())
console.log(number.toString()[3]) // Result is fine
let bigNumber = 1234567891111111111111111111111111111n // <-- n suffix, literal syntax
console.log(bigNumber.toString())
console.log(bigNumber.toString()[30]) // result
let bigNumber2 = BigInt('1234567891111111111111111111111111111') // <-- also works as a string, in case you can't use the literal for some reason
console.log(bigNumber2.toString())
console.log(bigNumber2.toString()[30]) // result

String List value is different in javascript and java action file

Good day,
In my java action file, I have a list:
protected ArrayList< String > deletedCorpRegisteredAccountRefNo = new ArrayList< String >( );
And then I put in some data inside this ArrayList, and print it out:
System.out.println( "deletedCorpRegisteredAccountRefNo : "+
deletedCorpRegisteredAccountRefNo );
And the result display correctly:
deletedCorpRegisteredAccountRefNo : [0000000000000234324, 0000000000015422629]
Then I go to my jsp and my javaScript function, I tried to assign this ArrayList value to a var call refNoList, and print out:
var refNoList = ${actionBean.deletedCorpRegisteredAccountRefNo};
console.log(refNoList);
I am expected I will see my browser console will print out something like what I see in Java System.out.println(), but I get another result:
[80084, 15422629]
The 15422629 is still acceptable, because maybe JavaScript auto trim the 0. But not understand why 0000000000000234324 will become 80084, this is totally different.
I try to google to find what is the root cause, but fail to get it, I think I am asking the wrong question in Google.
Kindly advise.
If a JavaScript number starts with zero, it can be interpreted as an octal value. And
var x = 0234324;
console.log(x);
this writes out 80084, because in decimal, this is the same value, as 234324 in octal.
You need to trim the trailing zeroes from the strings, and it will work as you want it to.
Other number definitions
In JavaScript the numbers can be interpreted as binary, octal, decimal or hexadecimal. Here a little list of different literals:
123 - normal decimal
0123 - octal: decimal value is 83
0x123 - hexadecimal: decimal value is 291
0o123 - octal: decimal value is 123
0b101 - binary: decimal value is 5
The problem with the second example (0123) is that it is only interpreted as octal when it is possible. E.g. 09123 and 081 will be interpreted as decimal. Moral of the story, you should not depend on this behaviour, if you need an octal, use 0o explicitely, if you need decimals, trim those zeroes.
Fixing the issue
To parse the number as a decimal, no matter what, you can simply give the radix value as a parameter to parseInt(number, radix):
var x = "000000123";
console.log(parseInt(x, 10)); // prints out 123

Javascript Checking for NaN - Results not as expected

I have an application that reads in a number via ajax, the number is hexadecimal and I parse it and convert to decimal.
The numbers come in through a wireless serial link and are not 100% reliable so I need to check them before I start processing the data. The numbers take the form ****025781610403e5**** for example. The **** is just a way of checking the start and end of the number that I have used in the past with non web based projects and could be changed.
Anyway to my question at last: As part of error checking I thought I would check for NaN as I do get NaN errors when I have been testing but while *1234 gives a positive NaN 12**34 does not, why is that? and what else can I do to test?
Here is some of the code I have used, please note I am fairly new to javascript.
function readSliceConvert()
{
functionReadForm()
testVal = hexString.slice(4,18);
document.getElementById("battDb4").innerHTML=testVal;
testNum1 = h2d(testVal)
document.getElementById("battDb5").innerHTML=testNum1.toString();
testNum2 = parseInt(testVal);
document.getElementById("battDb6").innerHTML=testNum2.toString();
if (isNaN(testNum2))
{
errorCount++;
document.getElementById("battDb3").innerHTML=errorCount.toString();
document.getElementById("battDb4").innerHTML=testVal;
return;
}
}
That's because you are using parseInt, it will silently ignore characters at the end of the string when there are some digit in the beginning of the string that it can parse.
I don't know what your h2d function is doing, but it seems that you are converting the hexadecimal string to a number, then to a string in decimal form, then back to a number. I don't see any reason why the output of parsing the hexadecimal string couldn't be a number.
For example like this, returning null if the parsing fails:
function h2i(str) {
var num = 0;
var digits = "0123456789abcdef";
str = str.toLowerCase();
for (var i = 0; i < str.length; i++) {
var n = digits.indexOf(str.substr(i, 1));
if (n == -1) return null;
num = num * 16 + n;
}
return num;
}
Demo: http://jsfiddle.net/Guffa/6yAaP/
Usage:
testVal = hexString.slice(4,18);
document.getElementById("battDb4").innerHTML = testVal;
testNum = h2i(testVal)
document.getElementById("battDb5").innerHTML = testNum.toString();
if (testNum == null)
{
errorCount++;
document.getElementById("battDb3").innerHTML = errorCount.toString();
document.getElementById("battDb4").innerHTML = testVal;
return;
}
Do you know what parseInt() does?
From MDN
parseInt is a top-level function and is not associated with any
object.
The parseInt function converts its first argument to a string, parses
it, and returns an integer or NaN. If not NaN, the returned value will
be the decimal integer representation of the first argument taken as a
number in the specified radix (base). For example, a radix of 10
indicates to convert from a decimal number, 8 octal, 16 hexadecimal,
and so on. For radices above 10, the letters of the alphabet indicate
numerals greater than 9. For example, for hexadecimal numbers (base
16), A through F are used.
If parseInt encounters a character that is not a numeral in the
specified radix, it ignores it and all succeeding characters and
returns the integer value parsed up to that point. parseInt truncates
numbers to integer values. Leading and trailing spaces are allowed.
Run the code in the console
console.log( parseInt("12**34",10) );
So you are running isNaN against a number since parseInt returns 12.
When you have the * as the first character, there are no leading numbers to return.
console.log( parseInt("*1234",10) );
You're seeing weird behaviour because isNan is broken (see the mozilla docs for details).
A better way to test your data is correctly formatted would be a quick regular expression, like serial.test(/^\d+$/), which will succeed if the entire serial is entirely numeric, or serial.test(/^\*{4}\d+\*{4}$/) which will succeed if the serial is four asterisks, followed by one or more number, followed by another four asterisks.
Update: #Guffa's answer is correct, and should be accepted, but I'll leave this here as I think there's a valid argument in the bigger picture that you could better accomplish what you're trying to do with a regular expression.
Running test on the string executes the supplied regular expression, and returns true if it matches the string.
Regular expressions are just patterns describing text, which can be incredibly complex or as simple as the example I've given (\d+ means match a number (\d) one or more times (+), with anchors for the beginning (^) and end ($) of the string to indicate that we want to match the whole string, not just part of it. They're ridiculously useful, so it's almost certainly worth taking the time to learn the basics of how they work, and expand you knowledge over time. There's a great tutorial on regular-expressions.info that'll get you started in no time.

Categories