Hi can anyone let me know the logic to convert the string
into number
with two decimal using inbuilt JavaScript methods
The input value is a JSON
string
Ex1: 123 just need to convert to 1.23
Ex2: 153 to 1.53
Ex3: 100 to 1.00
Hi can anyone let me know the logic to convert the string
into number
with two decimal using inbuilt JavaScript methods
The input value is a JSON
string
Ex1: 123 just need to convert to 1.23
Ex2: 153 to 1.53
Ex3: 100 to 1.00
I suggest dividing by 100 by also using toFixed(2)
to ensure that we always end up with at most two decimal places, which seems to be part of your reporting requirement.
var input = 123.456;
console.log(input);
output = (input / 100).toFixed(2);
console.log(output);
This will work for you:
console.log((Number('123') / 100).toFixed(2));
console.log((Number('100') / 100).toFixed(2));
console.log((Number('156') / 100).toFixed(2));
console.log((Number('123') / 100).toFixed(2));
console.log((Number('100') / 100).toFixed(2));
console.log((Number('156') / 100).toFixed(2));
console.log((Number('100') / 100).toFixed(2));
Note:- You can use the inbuilt Number() function to convert the string to a number, then divide by 100.
You can use the inbuilt Number() function to convert the string to a number, then divide by 100:
function convertNumber(input) {
return (input) ? (Number(input) / 100).toFixed(2): null;
}
console.log("Result:", convertNumber("123"));
console.log("Result:", convertNumber("153"));
console.log("Result:", convertNumber("176"));
console.log("Result:", convertNumber("100"));
console.log("Result:", convertNumber(null));
You can use parseInt() function to convert string to integer
For example:
var x = parseInt("100")