I am using BigInt(20) datatype for auto Increment id in mysql database.
and when the integer value is so big then how can I handle this as after the number precision of javascript, it won't to allow to insert and read any number Value. So how can I achieve this.
Read about the big-integer libraries but I won't the expected result
Example:-
var x = 999999999999999999999999999999999999999;
How can I print the same number without using its exponential value and any garbage value ?
I tried like that
var BigNumber = require('big-number');
var x = new BigNumber(999999999999999999999999999999999999999, 10);
console.log(x);
Example2:-
If I get the last inserted Id, then how can I handle this value
connection_db.query('INSERT INTO tableName SET ?', tableData,
function (error1, results1, fields1) {
error1){
// Db error
}else{
var lastInserted = new BigNumber(results1.insertId);
console.log(lastInserted);// still wrong value
}
});
You can only pass/show large numbers like that as strings:
var BigNumber = require('big-number');
var x = new BigNumber('999999999999999999999999999999999999999', 10);
console.log(x.toString())
However, in the end, it's up to the MySQL driver how it handles large numbers like this, because it does have to take into account Number.MAX_SAFE_INTEGER.
For instance, the mysql module has various options (supportBigNumbers and bigNumberStrings) that relate to handling BIGINT.
Related
For example if a user write 12, then when its passed to the backend to be passed as 12.00.
var contract_hrs = document.getElementById("eng_contract_hours");
you can use .toFixed(number to get value) at the time you are getting the number in backend
//in backend
let num = 12;
let n = num.toFixed(2); //12.00
Basically you cant, interaction between the two is based upon sending strings or binary. But what you can do is to create an enum for that. It will look kinda like this.
var contract_hrs = document.getElementById("eng_contract_hours");
var input_enum = {hrs: contract_hrs.value, type: int}
You can pass it to your backend and consume it the way you want based on the type property.
And in JS already 12 as a number is 12.00.
I'm setting up a custom payment gateway using an API, The API request the transaction_details.gross_amount as a number not minimum than 10000 like this:
transaction_details: {
gross_amount: 100000,
}
What I want is that this gross_amount get some value as the user input field:
I try to like this but couldn't help:
var trying = document.getElementById('give-amount').value;
var gross_amount = new String("");
var requestBody =
{
transaction_details: {
gross_amount: trying,
}
}
Its good I get some user input amount in the 'give-amount' field but still giving me the error transaction_details.gross_amount is not a number.
The question is how to change the gross_amount to get the user input value without getting the error that is not a number.
You can parse the integer using parseInt and then further pass it down to the body.
Also, you don't need to declare a new string.
To add, when doing parseInt over a string (or some other data type), it might return NaN i.e. Not a Number - so you wouldn't want to send that to the server too.
For that, you can add a safe check that if parseInt fails, then send 0 or any other value that you'd like.
var trying = parseInt(document.getElementById('give-amount').value) || 0,
requestBody = {
transaction_details: {
gross_amount: trying
}
};
If you're interested in having decimal values,
then you can use parseFloat instead of parseInt.
I am fetching data from bigquery which I need to store in MongoDB as integer, so that I can perform operations on that data in Mongo. Even though the data types of columns in bigquery is Integer, its nodejs api is returning string in its Javascript object. E.g. I'm getting results that look like [{row1:'3',row2:'4',row3:'5'},{row1:'13',row2:'14',row3:'15'}...]
typeof gives string on each element of object. I can run a loop and convert each element to integer, but that is not scalable on the data set. Also, I don't want all strings to be converted to integers, only ones which are stored as integer in bigquery. I'm using gcloud module in nodejs to fetch data.
assuming you know where the type property is on the response, something like this would work.
var response = [{type: 'Integer', value: '13'} /* other objects.. */];
var mappedResponse = response.map(function(item) {
// Put your logic here
// This implementation just bails
if (item.type != 'Integer') return item;
// This just converts the value to an integer, but beware
// it returns NaN if the value isn't actually a number
item.value = parseInt(item.value);
// you MUST return the item after modifying it.
return item;
});
This still loops over each item, but immediately bails out if it's not what we're looking for. Could also compose multiple maps and filters to generalize this out.
The only way to get by this is by first applying a filter, but this basically achieves the same thing as our initial type check
var mappedResponse = response
// Now we only deal with integers in the map function
.filter(x => x.type == 'Integer)
.map(function(item) {
// This just converts the value to an integer, but beware
// it returns NaN if the value isn't actually a number
item.value = parseInt(item.value);
// you MUST return the item after modifying it.
return item;
});
BigQuery deliberately encodes integers as strings when returning them via API to avoid loss of precision for large values. For now, the only option is to parse them on the client side.
I am looking for a way to generate a unique ID for nosql database. Unlike relational database there is no idea of rows which means there is no last row to increment from.
The most common way to handle this is to use UUID's. But my problem is I need to add another ID (other than the UUID) which needs to be:
Unique
Unsigned Int32
Total data could reach around 50,000,000. So how would you generate somewhat unique uint32 ID's?
The UInt32 value type represents unsigned integers with values ranging from 0 to 4,294,967,295.
Only generated when a new user registers.
3 Id's are given to each new user.
Currently using Couchbase Server.
This problem has already been solved - I would suggest using the atomic Increment (or Decrement) functions in Couchbase - these are a common pattern to generate unique IDs.
Whenever the incr() method is called, it atomically increments the counter by the specified value, and returns the old value, therefore it's safe if two clients try to increment at the same time.
Pseudocode example (I'm no Node.JS expert!):
// Once, at the beginning of time we init the counter:
client.set("user::count", 0);
...
// Then, whenever a new user is needed:
nextID = client.incr("user::count", 1); // increments counter and returns 'old' value.
newKey = "user_" + nextID;
client.add(newKey, value);
See the Node.JS SDK for reference, and see Using Reference Doucments for Lookups section in the Couchbase Developer Guide for a complete usage example.
Here's a function that returns a unique identifier each time it's called. It should be fine as long as the number of items does not exceed the range of 32-bit integers, which seems to be the case given the described requirements. (warning: once the array of UIDs fills up, this enters an infinite loop. You may also want to create some sort of a reset function that can empty the array and thus reset the UID when necessary.)
var getUID = (function() {
var UIDs = [];
return function() {
var uid;
do {
uid = Math.random() * Math.pow(2, 32) | 0x0;
} while (UIDs[uid] !== undefined);
return UIDs[uid] = uid;
};
}());
if you will call this insert method by passing "user" as key then your docId will be auto increment as
user_0
user_1
user_2
etc...
Please note that couchbase will show one extra row in your bucket with key as meta id and next counter value as doc value. Do not get surprised if you use query like select count(*) total from table; as it will show one more than real count, to avoid use where clause so that this row won't be counted.
public insert(data: any, key: string) {
return new Promise((resolve, reject) => {
let bucket = CouchbaseConnectionManager.getBucket(`${process.env.COUCHBASE_BUCKET}`)
bucket.counter(key, 1, {initial:0}, (err:any, res:any)=>{
if(err){
this.responseHandler(err, res, reject, resolve);
}
const docId = key + "_" + res.value;
bucket.insert(docId, data, (error:any, result:any) => {
this.responseHandler(error, result, reject, resolve);
});
});
});
}
I've read a lot about Data Types in javascript, but found nothing about long int.
I need to know how to define Long Int in javascript.
The reason is the input of following methods of Range object accepts Long data type as second parameter :
var storedSelection = document.createRange();
storedSelection.setStart(document.body, );
storedSelection.setEnd(document.body, );
This Image is captured from WebStorm IDE, please pay attention to type mentioned in this image:
If you've read a lot about JavaScript's data types as you say then you should already know that:
JS variables are loosely typed. That is, when you declare a variable you don't give it a type (only assigned values have a type).
Any given variable can be assigned values of different types at different times. That is, having set x = 12 you can later set x = "some string" or x = { some : "object" } and so forth.
JS only has one number type, floating point numbers (IEEE-754 doubles), so generally speaking no distinction is made between integers and decimals.
I don't know where you read that the range methods accept a "long int data type" as a parameter, but for that parameter you can pass in a JS variable that you know holds an integer, or a numeric literal, or even a function call that returns a number:
function getNumber() {
return 15;
}
var myVariable = 20;
var storedSelection = document.createRange();
storedSelection.setStart(document.body, 12);
storedSelection.setEnd(document.body, myVariable);
storedSelection.setEnd(document.body, getNumber() );
Further reading: https://developer.mozilla.org/en/JavaScript/Guide/Values,_Variables,_and_Literals
P.S. If you have a non-integer value as a result of a calculation, say you're calculating your range by dividing the total length by three or something, you can force the result to be an integer by rounding to the nearest integer with Math.round() or rounding down with Math.floor() or rounding up with Math.ceil(). See also the Math object.