All files / libs/amalia-lang/formula/evaluate/shared/src/functions/string/to-number index.ts

100% Statements 41/41
100% Branches 3/3
100% Functions 1/1
100% Lines 41/41

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 421x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
import { AmaliaFunctionCategory, AmaliaFunctionKeys, type AmaliaFormula } from '@amalia/amalia-lang/formula/types';
 
import { AmaliaFunctionDefault } from '../../AmaliaFunction';
 
export const stringToNumber = new AmaliaFunctionDefault<[string | null | undefined], number>({
  name: AmaliaFunctionKeys.toNumber,
  category: AmaliaFunctionCategory.STRING,
 
  nbParamsRequired: 0,
  description: 'Convert a string to a number',
 
  exec: (stringToConvert) => {
    const number = Number(stringToConvert);
    return Number.isNaN(number) ? 0 : number;
  },
 
  params: [{ name: 'string', description: 'String: variables, fields, properties, string', defaultValue: null }],
 
  examples: [
    {
      desc: 'Returns 5',
      formula: 'toNumber("5")' as AmaliaFormula,
      result: 5,
    },
    {
      desc: 'Returns 3.32',
      formula: 'toNumber("3.32")' as AmaliaFormula,
      result: 3.32,
    },
    {
      desc: 'Returns -12',
      formula: 'toNumber("-12")' as AmaliaFormula,
      result: -12,
    },
    {
      desc: 'Returns 0 when string cannot be converted to number',
      formula: 'toNumber("hello")' as AmaliaFormula,
      result: 0,
    },
  ],
});