Javascript String to Float conversion inside string building - javascript

I am preparing database insert query in Snowflake Stored Procedure.
My expected output is 2.0
console.log(`INSERT INTO MY_SCHEMA.MONITORING (COUNT, MESSAGE) VALUES (` + parseFloat('1.0') + 1 + `, 'DUM')`);
console.log(parseFloat('1.0') + 1);
Output of a 1st Line:
INSERT INTO MY_SCHEMA.MONITORING (COUNT, MESSAGE) VALUES (11, 'DUM')
Output of a 2nd Line:
2
What is happening at a first line and why its returning 11 instead of 2 ?

Remember that you are concatenating a string, so if you want to make an addition before the concat, you should use a parenthesis (parseFloat('1.0') + 1). Use the toFixed() function to indicate the decimals after comma or dot:
console.log(`INSERT INTO MY_SCHEMA.MONITORING (COUNT, MESSAGE) VALUES (` + (parseFloat('1.0') + 1).toFixed(1) + `, 'DUM')`);
console.log((parseFloat('1.0') + 1).toFixed(1));

You're converting to float and then immediately concatenating into the string. Instead, you can make use of your template literal.
`INSERT INTO MY_SCHEMA.MONITORING (COUNT, MESSAGE) VALUES (${parseFloat('1.0') + 1}, 'DUM')`

Related

How to slice part of string from the middle to the end using javascript

I have string like this:
река Марица - гр. Първомай + Maritsa - 132543 - HPoint-Water level
I want to get only Maritsa - 132543 - HPoint-Water level with javascript.
For now I get the string and console log all string, but I need to cut the cyrillic string and - before Maritsa.
The problem is that the loaded names are always different. Is there a way to delete everything before the + including it and show everything after the +
You could replace the unwanted part.
const s = 'река Марица - гр. Първомай + Maritsa - 132543 - HPoint-Water level';
console.log(s.replace(/.*\+\s?/, ''));
You can combine String.prototype.indexOf (which returns the first occurence of a char) and Array.prototype.slice (to return the string only after a certain index, here after the + and the space after it) :
const name = 'река Марица - гр. Първомай + Maritsa - 132543 - HPoint-Water level'
const cutString = string => string.slice(string.indexOf('+') + 2)
// add 2 to also remove the + and the space after it ^
console.log(`"${ cutString(name) }"`)
Hope it helped you !

Pushing array into array and using it throws NaN

I've got a variable called colorHM:
var colorHM = "50,50,74,255,100,255,4,3,50".
Now I'm using this snippet here to cut it into pieces with the following scheme: R,g,b,R,g,b,R,g,b, and again to var a = R,g,b and var b = R,g,b etc...
var firstColorHM = colorHM.split(",", 3);
firstColorHM = firstColorHM.toString();
var firstColorHMA = firstColorHM.split(",");
firstCMA.push(firstColorHMA[0]);
firstCMA.push(firstColorHMA[1]);
firstCMA.push(firstColorHMA[2]);
But using it to calculate distance = eDist(firstCMA, firstCTA) gives me NaN.
function eDist (col1, col2) {
var rmean = ((col1[0] + col2[0]) / 2);
var dR = (col1[0] - col2[0]);
var dG = (col1[1] - col2[1]);
var dB = (col1[2] - col2[2]);
return Math.sqrt((2 + (rmean / 256)) * Math.pow(dR, 2) + (4 * Math.pow(dG, 2)) + ( 2 + ((255- rmean) / 256)) * Math.pow(dB, 2));
}
Using firstCMA.push(10); firstCMA.push(20); firstCMA.push(30); instead of firstCMA.push(firstColorHMA[0]);.. makes it work again.
The variable firstCTA is left out, but parsed the same way.
I simply checked if the Arrays were working by trying to call different indexes from the array, which worked.
Why does pushing numbers work but pushing firstColorHMA[0] doesnt?
Thanks in advance!
Like the comments says, when you split() a string, the generated array will contain strings:
The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
So actually the array firstColorHMA holds numbers as strings, an easy fix to this, will be using the unary plus to cast the array items to numbers, like this:
firstCMA.push(+firstColorHMA[0]);
firstCMA.push(+firstColorHMA[1]);
firstCMA.push(+firstColorHMA[2]);
Or alternatively, use a more explicit logic like:
firstCMA.push(Number(firstColorHMA[0]));
firstCMA.push(Number(firstColorHMA[1]));
firstCMA.push(Number(firstColorHMA[2]));

Prevent Javascript from replacing beginning of string with NaN?

I am work on some OData query calls to Microsoft CRM and need my query in a very specific format.I am passing parameters to a function which then adds the URL to my query. What I am passing my retrieve function is as follows:
webAPI.REST.retrieveEntity(
"EntityDefinition",
id,
+ "/Attributes(LogicalName='" + logicalAttribute + "')"
+ "/Microsoft.Dynamics.CRM.PicklistAttributeMetadata"
+ "?$select=LogicalName&$expand=OptionSet"
, null)
In debugging my parameter with the query options is:
"NaNmylogicalattribute')/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet"
As you can see, my "/Attributes(LogicalName=" was replaced with "NaN". How do I prevent this from occurring?
Here is the problem:
id,
+ "/Attributes(LogicalName='" + logicalAttribute + "')"
Since you aren't starting with a String, the leading + is coercing your String into a Number (it isn't a Number, hence NaN). Just remove that first leading + and it will work:
id,
"/Attributes(LogicalName='" + logicalAttribute + "')"

How to customize JSON output on the first level ONLY using JavaScript's stringify() method?

I use stringify() method in JavaScript to convert a list of objects to a string, but I need to customize the output on the first level ONLY like the following:
[
/*T01*/ {"startX":55,"endX":109,"sartY":0,"endY":249},
/*T02*/ {"startX":110,"endX":164,"sartY":0,"endY":249},
/*T03*/ {"startX":165,"endX":219,"sartY":0,"endY":249},
/*T04*/ {"startX":220,"endX":274,"sartY":0,"endY":249},
/*T05*/ {"startX":275,"endX":329,"sartY":0,"endY":249},
/*T06*/ {"startX":330,"endX":384,"sartY":0,"endY":249},
/*T07*/ {"startX":385,"endX":439,"sartY":0,"endY":249},
/*T08*/ {"startX":440,"endX":494,"sartY":0,"endY":249},
/*T09*/ {"startX":495,"endX":549,"sartY":0,"endY":249},
/*T10*/ {"startX":550,"endX":604,"sartY":0,"endY":249}
]
Now there are other parameters in stringfy() method, replacer and space, can't I use them to format my output like the aforementioned format including:
tabs
spaces
comments
You are not going to get JSON.parse to make that output since it is not valid JSON. But if you want to have something rendered like that, it is a simple loop and string concatenation.
var details = [
{"startX":55,"endX":109,"sartY":0,"endY":249},
{"startX":110,"endX":164,"sartY":0,"endY":249},
{"startX":165,"endX":219,"sartY":0,"endY":249},
{"startX":220,"endX":274,"sartY":0,"endY":249},
{"startX":275,"endX":329,"sartY":0,"endY":249},
{"startX":330,"endX":384,"sartY":0,"endY":249},
{"startX":385,"endX":439,"sartY":0,"endY":249},
{"startX":440,"endX":494,"sartY":0,"endY":249},
{"startX":495,"endX":549,"sartY":0,"endY":249},
{"startX":550,"endX":604,"sartY":0,"endY":249}
];
var out = "[\n" + details.map(function(val, i) {
var id = "\t/*T" + ("0" + (i + 1)).substr(-2) + "*/\t";
return id + JSON.stringify(val);
}).join(",\n") + "\n]";
console.log(out);

How can I correctly convert into number these string object retrieved from input tag of a form by this JQuery function? [duplicate]

This question already has answers here:
Javascript to convert string to number? [duplicate]
(4 answers)
Closed 7 years ago.
I am pretty new in JavaScript and JQuery and I am having a strange behavior with a simple mathematical sum into a JQuery function that retrieve numbers from some input field inside a JSP page (I can't put a JSFiddle because the values are take from jsp model object)
So, this is my JQuery function:
$("#variazioneUlterioreSaldoInput").bind('change keyup', function() {
console.log("VALUE CHANGED !!!");
var ulterioreSaldo = $("#variazioneUlterioreSaldoInput").val(); // Non ha separatori di migliaia o di decimanli quindi non devo eseguire replace
var saldo = $("#saldo").val().replace(/[^0-9,]/g, '').replace(",",".");
var anticipo = $("#anticipo").val().replace(/[^0-9,]/g, '').replace(",",".");
var totalePagamento = ulterioreSaldo + saldo + anticipo;
console.log("ulterioreSaldo: " + ulterioreSaldo );
console.log("ulterioreSaldo type: " + typeof ulterioreSaldo);
console.log("saldo: " + saldo);
console.log("saldo type: " + typeof saldo);
console.log("anticipo: " + anticipo);
console.log("anticipo type: " + typeof anticipo);
console.log("totalePagamento: " + totalePagamento);
console.log("totalePagamento type: " + typeof totalePagamento);
});
that retrieve and sum 3 values obtained from 3 differents input fields.
So for the values retrieved from the input tags having id="saldo" and id="anticipo" I apply a replace with 2 regex because these are strings that represent formatted number so before sum I have to obtain a plain number.
The problem is that when I perform the sum of these values by this line:
var totalePagamento = ulterioreSaldo + saldo + anticipo;
I obtain this wrong outout related to the sum: totalePagamento: 0.010.004499.48, this is the entire log into the FireBug Console.
VALUE CHANGED !!!
ulterioreSaldo: 0.01
ulterioreSaldo type: string
saldo: 0.00
saldo type: string
anticipo: 4499.48
anticipo type: string
totalePagamento: 0.010.004499.48
totalePagamento type: string
As you can see I have also printed the type of the retrieved objects and seems that are String and not Number so when I use the + operator these values are concatenated and not summed.
How can I correctly converts these values into Number and sum it?
Since you are adding decimal numbers try using parseFloat method:
var totalePagamento = parseFloat(ulterioreSaldo) + parseFloat(saldo) + parseFloat(anticipo);
And if you want only 2 digits after decimal use:
totalePagamento.toFixed(2);
use parseFloat() to sum the values
var totalePagamento = parseFloat(ulterioreSaldo) + parseFloat(saldo) + parseFloat(anticipo);
totalePagamento = totalePagamento.toFixed(2); //it will set floating point to 2 values e.g. 40.22
You have to use parseFloat() function to convert string into numbers. The parseFloat() function parses a string argument and returns a floating point number.
$(document).ready(function(){
var ulterioreSaldo = "0.01";
var saldo = "0.0";
var anticipo = "4499.48";
var sum = parseFloat(ulterioreSaldo) + parseFloat(saldo) + parseFloat(anticipo);
alert(sum);
});
Here is a Demo for the same.

Categories