Javascript: Convert string to number but keep decimal

e_wilber
Tera Guru

I have a currency field that stores a value in this format: 'USD;1234.05' so it's storing as a string.

I am splitting on ; to just get the number returned (as a string).
var amnt = newValue.split(/;/);

My question is now that the number is a string (in this case it is 1234.05), how do I convert it to a number and keep the decimal?

I have tried:

var str = '11,110.05';
gs.print('String: ' + str);

var strInt = parseInt(str);
gs.print('Int: ' + strInt);

var flt = parseFloat(str).toFixed(2);
gs.print('Float: ' + flt);

Which is returning

*** Script: String: 11,110.05
*** Script: Int: 11
*** Script: Float: 11.00

Int and Float are changing the number completely. I just need the exact number and decimal to come through so I can compare it to another number. In the real example I want 11,110.05 returned as a number so I can compare it to 5000 to see if it's greater than 5,000.

1 ACCEPTED SOLUTION

-O-
Kilo Patron
Kilo Patron

Not sure if it is supported in Portal (or Workspace), but in Platform UI (UI16/Polaris) GlideForm has a method to return the value as a Number:

g_form.getDecimalValue('<currency field name>');

View solution in original post

6 REPLIES 6

vikramjkn
Tera Contributor

I suppose, in that case, we can do something like this

 

var number = parseFloat("11,110.05".replace(/,/g, ''));
console.log(number);

//do comparison

//get it formatted again
console.log(Intl.NumberFormat('en-US').format(number));

 or may be some more detailed approach

function parseNumber(value, locales = navigator.languages) {
  const example = Intl.NumberFormat(locales).format('1.1');
  const cleanPattern = new RegExp(`[^-+0-9${ example.charAt( 1 ) }]`, 'g');
  const cleaned = value.replace(cleanPattern, '');
  const normalized = cleaned.replace(example.charAt(1), '.');

  return parseFloat(normalized);
}

const corpus = {
  '1.123': {
    expected: 1.123,
    locale: 'en-US'
  },
  '1,123': {
    expected: 1123,
    locale: 'en-US'
  },
  '2.123': {
    expected: 2123,
    locale: 'fr-FR'
  },
  '2,123': {
    expected: 2.123,
    locale: 'fr-FR'
  },
}


for (const candidate in corpus) {
  const {
    locale,
    expected
  } = corpus[candidate];
  const parsed = parseNumber(candidate, locale);

  console.log(`${ candidate } in ${ corpus[ candidate ].locale } == ${ expected }? ${ parsed === expected }`);
}

Source: https://stackoverflow.com/questions/11665884/how-can-i-parse-a-string-with-a-comma-thousand-separato...

OK, but how is that better than

 

 

g_form.getDecimalValue('<currency field name>');

 

 

not to mention are you sure navigator.languages will hold what the user selects in the ServiceNow profile?