To Number
Is a function that convert a value to a number.
๐ฌ Usage
<script>
import {to_number} from "@sveu/shared"
</script>
{to_number("1.5", {method: "int"})}
<hr/>
{to_number("edc", {nan_to_zero: true})}
๐ฉโ๐ปAPI
๐ป Arguments
Name | Description | Type | Required |
---|---|---|---|
value | The value to be converted | string | number | Yes |
๐ Options
Name | Description | Type | Default |
---|---|---|---|
method | The method to be used to convert | "int" | "float" | float |
nan_to_zero | Convert NaN to zero | boolean | False |
radix | The base in mathematical numeral systems passed to parseInt. | number | undefined |
โฉ๏ธ Returns
A number.
๐งช Playground
Source Code ๐
Source Code
import type { ToNumberOptions } from "../utils"
/**
* Convert a value to a number.
*
* @param value - The value to convert to a number.
*
* @param options - Options to control the conversion.
*
* @returns The converted number.
*/
export function to_number(
value: number | string,
options: ToNumberOptions = {}
): number {
const { method, radix, nan_to_zero } = options
let _method: "parseFloat" | "parseInt" = "parseFloat"
if (method === "int") _method = "parseInt"
let resolved =
typeof value === "number" ? value : Number[_method](value, radix)
if (nan_to_zero && isNaN(resolved)) resolved = 0
return resolved
}
Last update: 2023-03-07
Authors: Mohamed-Kaizen