Skip to content

Conversion Functions

Functions for converting between types. EverSharp has no implicit type conversion except string concatenation with + operator.


To Number

$ToNumber

Converts string to decimal number.

Signature: $ToNumber(stringValue)

Parameters:

  • stringValue (string): Numeric string to convert

Returns: (decimal) Converted number

Examples:

num = $ToNumber("42"); // 42
decimal = $ToNumber("3.14159"); // 3.14159
negative = $ToNumber("-100"); // -100

// From user input
input = "1234.56";
value = $ToNumber(input);

// ERROR if not valid number
// invalid = $ToNumber("abc");                  // Runtime error

.ToNumber()

Instance method to convert string to number.

Signature: stringValue.ToNumber()

Parameters: None (instance method)

Returns: (decimal) Converted number

Examples:

text = "42";
num = text.ToNumber(); // 42

price = "19.99";
value = price.ToNumber(); // 19.99

// Chained operations
trimmed = "  100  ";
num = trimmed.Trim().ToNumber(); // 100

To String

$ToString

Converts any value to string.

Signature: $ToString(value)

Parameters:

  • value (any): Value to convert

Returns: (string) String representation

Examples:

// Numbers
str = $ToString(42); // "42"
strDecimal = $ToString(3.14); // "3.14"

// Booleans
strBool = $ToString(true); // "True"

// Dates
date = $Now();
strDate = $ToString(date);

// In concatenation
message = "Count: " + $ToString(count);

.ToString()

Instance method to convert value to string.

Signature: value.ToString()

Parameters: None

Returns: (string) String representation

Examples:

num = 100;
str = num.ToString(); // "100"

flag = true;
strFlag = flag.ToString(); // "True"

.ToString(format)

Instance method with format string.

Signature: value.ToString(formatString)

Parameters:

  • formatString (string): .NET format string

Returns: (string) Formatted string

Examples:

// Number formatting
value = 1234.5678;
formatted = value.ToString("F2"); // "1234.57" (2 decimals)
formatted = value.ToString("N2"); // "1,234.57" (with comma)

// Date formatting
date = $Now();
formatted = date.ToString("yyyy-MM-dd"); // "2024-01-15"
formatted = date.ToString("MM/dd/yyyy"); // "01/15/2024"
formatted = date.ToString("HH:mm:ss"); // "14:30:45"

To Date

$ToDate

Converts string to DateTime.

Signature: $ToDate(dateString)

Parameters:

  • dateString (string or DateTime): Date string to parse

Returns: (DateTime) Parsed date

Examples:

date1 = $ToDate("2024-01-15");
date2 = $ToDate("01/15/2024");
date3 = $ToDate("2024-01-15 14:30:00");

// Already DateTime - returns as-is
existing = $Now();
same = $ToDate(existing);

// ERROR if invalid format
// invalid = $ToDate("not a date");             // Runtime error

$ToDateUTC

Converts string to UTC DateTime.

Signature: $ToDateUTC(dateString)

Parameters:

  • dateString (string): Date string to parse as UTC

Returns: (DateTime) UTC date

Examples:

utcDate = $ToDateUTC("2024-01-15");
utcDateTime = $ToDateUTC("2024-01-15 14:30:00");

$ToDateOnly

Converts to DateOnly (date without time).

Signature: value.ToDateOnly()

Parameters: None (instance method)

Returns: (DateOnly) Date without time component

Examples:

dateTime = $Now();
dateOnly = dateTime.ToDateOnly();

dateStr = "2024-01-15";
date = $ToDate(dateStr).ToDateOnly();

To Array

.ToArray()

Deserializes a JSON string into an array.

Signature: jsonString.ToArray()

Parameters: None (instance method on string)

Returns: (InstanceArray) Deserialized array

Examples:

// Array of strings
jsonStr = '["Testing","Array","Stringification"]';
result = jsonStr.ToArray(); // ["Testing", "Array", "Stringification"]

// Array of numbers
numericStr = "[1,2,3]";
numbers = numericStr.ToArray(); // [1, 2, 3]

// Array of objects
objectsStr = '[{"Country":"United Kingdom"}, {"Country":"Spain"}]';
countries = objectsStr.ToArray(); // Array of dictionaries
firstCountry = countries[0].Country; // "United Kingdom"

// From C# integration
// Pass serialized array from external system
// result = serializedData.ToArray();

Notes:

  • Only works on string values containing valid JSON arrays
  • Throws RuntimeException if string is not valid JSON
  • Useful for deserializing data from external systems or API responses
  • Supports nested arrays and objects

To Dictionary

.ToDictionary()

Deserializes a JSON string into an object/dictionary.

Signature: jsonString.ToDictionary()

Parameters: None (instance method on string)

Returns: (Instance) Deserialized object/dictionary

Examples:

// Simple object
addressStr =
  '{"Line1":"22 Barnsbury Road","Line2":"","PostCode":"N1 0HD","Town":"London"}';
address = addressStr.ToDictionary();
line1 = address.Line1; // "22 Barnsbury Road"
town = address.Town; // "London"

// Nested object
personStr = '{"Name":"John Doe","Age":30,"Address":{"City":"London"}}';
person = personStr.ToDictionary();
name = person.Name; // "John Doe"
city = person.Address.City; // "London"

// From C# integration
// Pass serialized object from external system
// config = configString.ToDictionary();
// value = config.Setting;

Notes:

  • Only works on string values containing valid JSON objects
  • Throws RuntimeException if string is not valid JSON
  • Useful for deserializing configuration, API responses, or database records
  • Properties are accessed using dot notation
  • Supports nested objects and arrays within the object

To Boolean

EverSharp does not have automatic boolean conversion. Use explicit comparisons:

// Not supported:
// if (value) { }

// Must use explicit comparison:
if (value != null) {
}
if (count > 0) {
}
if (flag == true) {
}

Type Checking Patterns

Check for Null

if (value != null) {
  // Value exists
}

Validate Number String

function isNumeric(str) {
  if (str == null || str.Trim() == "") {
    return false;
  }

  // Try to convert
  // In real code, would need try-catch pattern
  // EverSharp doesn't have try-catch, so validation is limited

  return true; // Simplified
}

Safe Number Conversion

function tryToNumber(str, defaultValue) {
  if (str == null || str.Trim() == "") {
    return defaultValue;
  }

  // In practice, $ToNumber throws on invalid input
  // Real code would need validation before conversion

  return $ToNumber(str);
}

value = tryToNumber(input, 0);

Common Patterns

Pattern 1: Display Formatting

// Format currency
amount = 1234.56;
display = "$" + amount.ToString("F2"); // "$1234.56"

// Format percentage
rate = 0.0825;
display = (rate * 100).ToString("F2") + "%"; // "8.25%"

Pattern 2: Parse User Input

function parseInput(input) {
  cleaned = input.Trim();

  if (cleaned == "") {
    return null;
  }

  return $ToNumber(cleaned);
}

value = parseInput("  42.5  "); // 42.5

Pattern 3: Date String Formatting

date = $Today();
formatted = date.ToString("yyyy-MM-dd"); // ISO format

// Custom format
year = $Year(date);
month = $Month(date);
day = $Day(date);
custom = $ToString(year) + "-" + $ToString(month) + "-" + $ToString(day);

Pattern 4: Array to CSV

numbers = [1, 2, 3, 4, 5];
strings = numbers.Map((n) => $ToString(n));
csv = strings.Join(","); // "1,2,3,4,5"

// Or directly
csv = numbers.Reduce(
  (acc, n) => acc + (acc == "" ? "" : ",") + $ToString(n),
  "",
);

Pattern 5: Boolean to String

flag = true;
display = flag ? "Yes" : "No";

// Or
display = flag == true ? "Active" : "Inactive";

Type Conversion Table

From To Function Example
String Decimal $ToNumber(str) or str.ToNumber() $ToNumber("42")
Decimal String $ToString(num) or num.ToString() $ToString(42)
Any String $ToString(value) or value.ToString() $ToString(true)
String DateTime $ToDate(str) $ToDate("2024-01-15")
DateTime DateOnly date.ToDateOnly() $Now().ToDateOnly()
String Array jsonString.ToArray() "[1,2,3]".ToArray()
String Dictionary/Object jsonString.ToDictionary() jsonStr.ToDictionary()
Decimal String (formatted) num.ToString(format) num.ToString("F2")
DateTime String (formatted) date.ToString(format) date.ToString("yyyy-MM-dd")

No Implicit Conversion

EverSharp does not perform implicit type conversion:

// ERROR: Cannot add number to string implicitly
// result = 10 + "20";                          // ERROR

// Must convert explicitly
result = 10 + $ToNumber("20"); // 30

// String concatenation works with +
text = "Value: " + $ToString(10); // "Value: 10"

Format String Reference

Number Formats

Format Description Example Input Example Output
F2 Fixed-point, 2 decimals 1234.5678 "1234.57"
F0 Fixed-point, no decimals 1234.5678 "1235"
N2 Number with commas, 2 decimals 1234.56 "1,234.56"
C2 Currency format 1234.56 "$1,234.56"
P2 Percentage, 2 decimals 0.1234 "12.34 %"

Date Formats

Format Description Example Output
yyyy-MM-dd ISO date "2024-01-15"
MM/dd/yyyy US date "01/15/2024"
dd/MM/yyyy European date "15/01/2024"
HH:mm:ss 24-hour time "14:30:45"
hh:mm tt 12-hour time "02:30 PM"
yyyy-MM-dd HH:mm:ss ISO datetime "2024-01-15 14:30:45"

Best Practices

1. Always Validate Before Conversion

// Good
if (input != null && input.Trim() != "") {
  value = $ToNumber(input);
}

// Risky
value = $ToNumber(input); // May throw if invalid

2. Use Format Strings for Display

// Good
display = amount.ToString("F2");

// Less ideal
display = $ToString($Round(amount, 2));

3. Trim String Input Before Conversion

// Good
value = input.Trim().ToNumber();

// Risky
value = input.ToNumber(); // May fail if has whitespace

4. Handle Null Explicitly

// Good
if (value != null) {
  str = value.ToString();
} else {
  str = "";
}

// Risky
// str = value.ToString();  // Fails if value is null

Advanced Examples

Example 1: Parse and Format Currency

function formatCurrency(input) {
  if (input == null || input.Trim() == "") {
    return "$0.00";
  }

  cleaned = input.Trim().Replace("$", "").Replace(",", "");
  amount = $ToNumber(cleaned);

  return "$" + amount.ToString("F2");
}

formatted = formatCurrency("  $1,234.567  "); // "$1234.57"

Example 2: Date Formatter

function formatDate(date, style) {
  if (style == "iso") {
    return date.ToString("yyyy-MM-dd");
  } else if (style == "us") {
    return date.ToString("MM/dd/yyyy");
  } else if (style == "long") {
    return date.ToString("MMMM dd, yyyy");
  } else {
    return $ToString(date);
  }
}

formatted = formatDate($Today(), "iso"); // "2024-01-15"

Example 3: Data Export

function exportToCSV(records) {
  lines = records.Map((record) => {
    fields = [
      record.id.ToString(),
      record.name,
      record.amount.ToString("F2"),
      record.date.ToString("yyyy-MM-dd"),
    ];

    return fields.Join(",");
  });

  return lines.Join("\n");
}

Next Steps