-1

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

user2395000
  • 17
  • 1
  • 7

5 Answers5

2

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);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

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));
Sumit Ridhal
  • 1,359
  • 3
  • 14
  • 30
1

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.

Parth Raval
  • 4,097
  • 3
  • 23
  • 36
0

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));
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
0

You can use parseInt() function to convert string to integer

For example:

var x = parseInt("100")
ChauhanTs
  • 439
  • 3
  • 6