
String To Number
Downloads: 31
Download Description
Simple String To Number using TypeScript
//
// StringToNumber.ts
// Converts a String to a Number(Float)
// Written by @Fusedthreed – https://FusedThreeD.com
//
@customNode()
export class CustomNodeTS extends BasicScriptNode {
@input()
input: string;
@output()
result: number;
@output()
error: boolean;
execute() {
if (!this.input || this.input.length === 0) {
this.error = true;
return;
}
let isValid = true;
let hasDot = false;
for (let i = 0; i < this.input.length; i++) {
const char = this.input[i];
if (char === ".") {
if (hasDot) {
isValid = false; // multiple dots
break;
}
hasDot = true;
} else if (char === "-" && i !== 0) {
isValid = false; // minus sign not at start
break;
} else if (!"0123456789".includes(char) && char !== "." && char !== "-") {
isValid = false; // invalid character
break;
}
}
if (!isValid) {
this.error = true;
return;
}
const num = parseFloat(this.input);
if (isNaN(num)) {
this.error = true;
return;
}
this.result = num;
this.error = false;
}
}