Skip to content

Conversion Functions

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


To Number

.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

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

To String

.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"

date = $Now();
strDate = date.ToString();

// Not needed in concatenation: + converts the other operand to string
message = "Count: " + count;

.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"

.ToStringSafe()

Safely converts any value to string.

Signature: value.ToStringSafe()

Parameters: None

Returns: (string) String representation, or "" when the value is null

Examples:

name = null;
safe = name.ToStringSafe(); // ""

premium = 123.45;
text = premium.ToStringSafe(); // "123.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 a value to UTC DateTime.

Signature: value.ToDateUTC(timeZone?)

Parameters:

  • timeZone (string, optional): Timezone the value is expressed in. IANA or Windows timezone ID, or 2-letter ISO country code. When omitted, the value is converted from server local time (or kept as-is if already UTC).

Returns: (DateTime) UTC date

Examples:

utcDate = "2024-01-15".ToDateUTC();
utcDateTime = "2024-01-15 14:30:00".ToDateUTC();
madridMidnight = "2025-08-13".ToDateUTC("Europe/Madrid"); // 2025-08-12T22:00:00Z
spainMidnight = "2025-08-13".ToDateUTC("ES"); // same as above

Notes:

  • Useful when normalizing string dates to UTC before conversions or comparisons
  • $ConvertTimeToUtc(date, timeZone) is the global-function equivalent

.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:

EverSharp string literals can't contain double quotes, so JSON text with strings normally arrives as input data (for example, a variable set from C#).

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

// Array of strings, from input data
// jsonStr: ["Testing","Array","Stringification"]
result = jsonStr.ToArray(); // ["Testing", "Array", "Stringification"]

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

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:

The JSON text normally arrives as input data (for example, a variable set from C#), since EverSharp string literals can't contain double quotes.

// Simple object, from input data
// 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, from input data
// personStr: {"Name":"John Doe","Age":30,"Address":{"City":"London"}}
person = personStr.ToDictionary();
name = person.Name; // "John Doe"
city = person.Address.City; // "London"

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 str.ToNumber();
}

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 cleaned.ToNumber();
}

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 = year.ToString() + "-" + month.ToString() + "-" + day.ToString();

Pattern 4: Array to CSV

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

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

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 str.ToNumber() "42".ToNumber()
Decimal String num.ToString() num.ToString()
Any String value.ToString() flag.ToString()
String DateTime $ToDate(str) $ToDate("2024-01-15")
String UTC DateTime str.ToDateUTC(timeZone?) "2024-01-15".ToDateUTC()
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 convert strings to numbers implicitly. When either operand of + is a string, the other is converted to string and the two are concatenated:

// Concatenation, not addition
result = 10 + "20"; // "1020"

// Convert explicitly to add
result = 10 + "20".ToNumber(); // 30

// String concatenation works with +
text = "Value: " + 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 = input.ToNumber();
}

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

2. Use Format Strings for Display

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

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

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 = cleaned.ToNumber();

  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 date.ToString();
  }
}

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(",");
  });

  // String literals can't contain a newline, so return one CSV row per record
  return lines;
}

Next Steps