toInt
Converts a value to an integer. If the conversion fails, returns the default value.
Basic Usage
typescript
import { toInt } from 'radash'
console.log(toInt('123')) // 123
console.log(toInt('123.45')) // 123
console.log(toInt('abc', 0)) // 0
console.log(toInt(null, 1)) // 1
Syntax
typescript
function toInt(
value: any,
fallback?: number
): number
Parameters
value
(any): The value to convertfallback
(number, optional): The default value if conversion fails, default is 0
Return Value
Returns the converted integer. If conversion fails, returns the default value.
Examples
Basic Conversion
typescript
import { toInt } from 'radash'
console.log(toInt('123')) // 123
console.log(toInt('123.45')) // 123
console.log(toInt('0')) // 0
console.log(toInt('-123')) // -123
console.log(toInt('123abc')) // 123
Handling Invalid Values
typescript
import { toInt } from 'radash'
console.log(toInt('abc')) // 0 (default value)
console.log(toInt('abc', 1)) // 1 (custom default value)
console.log(toInt(null)) // 0
console.log(toInt(undefined)) // 0
console.log(toInt('')) // 0
console.log(toInt(' ')) // 0
Handling Number Types
typescript
import { toInt } from 'radash'
console.log(toInt(123)) // 123
console.log(toInt(123.45)) // 123
console.log(toInt(0)) // 0
console.log(toInt(-123)) // -123
console.log(toInt(Infinity)) // 0
console.log(toInt(-Infinity)) // 0
console.log(toInt(NaN)) // 0
Handling Boolean Values
typescript
import { toInt } from 'radash'
console.log(toInt(true)) // 1
console.log(toInt(false)) // 0
console.log(toInt('true')) // 0 (string 'true' is not a valid number)
console.log(toInt('false')) // 0
Handling Arrays and Objects
typescript
import { toInt } from 'radash'
console.log(toInt([])) // 0
console.log(toInt([1, 2, 3])) // 0
console.log(toInt({})) // 0
console.log(toInt({ key: 123 })) // 0
console.log(toInt(() => {})) // 0
Handling Special Strings
typescript
import { toInt } from 'radash'
console.log(toInt('123.45')) // 123
console.log(toInt('123abc')) // 123
console.log(toInt('abc123')) // 0
console.log(toInt('123abc456')) // 123
console.log(toInt('0x1A')) // 0 (hexadecimal string)
console.log(toInt('1e2')) // 100 (scientific notation)
Usage in Form Processing
typescript
import { toInt } from 'radash'
function processFormData(formData: FormData) {
const age = toInt(formData.get('age'), 18)
const score = toInt(formData.get('score'), 0)
const count = toInt(formData.get('count'), 1)
return { age, score, count }
}
// Mock form data
const mockFormData = new FormData()
mockFormData.append('age', '25')
mockFormData.append('score', '85.5')
mockFormData.append('count', 'abc')
const result = processFormData(mockFormData)
console.log(result) // { age: 25, score: 85, count: 1 }
Handling API Responses
typescript
import { toInt } from 'radash'
function processApiResponse(response: any) {
return {
id: toInt(response.id, 0),
count: toInt(response.count, 0),
rating: toInt(response.rating, 5),
price: toInt(response.price, 0)
}
}
const apiResponse = {
id: '123',
count: '45.67',
rating: 'invalid',
price: null
}
const processed = processApiResponse(apiResponse)
console.log(processed) // { id: 123, count: 45, rating: 5, price: 0 }
Handling Configuration Data
typescript
import { toInt } from 'radash'
function parseConfig(config: Record<string, any>) {
return {
port: toInt(config.port, 3000),
timeout: toInt(config.timeout, 5000),
maxConnections: toInt(config.maxConnections, 100),
retryCount: toInt(config.retryCount, 3)
}
}
const config = {
port: '8080',
timeout: 'invalid',
maxConnections: '50.5',
retryCount: null
}
const parsed = parseConfig(config)
console.log(parsed) // { port: 8080, timeout: 5000, maxConnections: 50, retryCount: 3 }
Handling User Input
typescript
import { toInt } from 'radash'
function validateUserInput(input: string, min: number, max: number) {
const value = toInt(input, min)
if (value < min) {
return { valid: false, value: min, message: `Value must be at least ${min}` }
}
if (value > max) {
return { valid: false, value: max, message: `Value must be at most ${max}` }
}
return { valid: true, value, message: 'Valid input' }
}
console.log(validateUserInput('25', 0, 100)) // { valid: true, value: 25, message: 'Valid input' }
console.log(validateUserInput('abc', 0, 100)) // { valid: false, value: 0, message: 'Value must be at least 0' }
console.log(validateUserInput('150', 0, 100)) // { valid: false, value: 100, message: 'Value must be at most 100' }
Handling Database Query Results
typescript
import { toInt } from 'radash'
function processDatabaseResult(result: any) {
return {
userId: toInt(result.user_id, 0),
score: toInt(result.score, 0),
attempts: toInt(result.attempts, 1),
level: toInt(result.level, 1)
}
}
const dbResult = {
user_id: '123',
score: '85.5',
attempts: 'invalid',
level: null
}
const processed = processDatabaseResult(dbResult)
console.log(processed) // { userId: 123, score: 85, attempts: 1, level: 1 }
Handling CSV Data
typescript
import { toInt } from 'radash'
function parseCSVRow(row: string[]) {
return {
id: toInt(row[0], 0),
age: toInt(row[1], 0),
score: toInt(row[2], 0),
rank: toInt(row[3], 1)
}
}
const csvRow = ['123', '25.5', '85.67', 'invalid']
const parsed = parseCSVRow(csvRow)
console.log(parsed) // { id: 123, age: 25, score: 85, rank: 1 }
Handling Mathematical Calculations
typescript
import { toInt } from 'radash'
function calculateAverage(values: any[]) {
const validNumbers = values
.map(val => toInt(val, null))
.filter(val => val !== null)
if (validNumbers.length === 0) {
return 0
}
const sum = validNumbers.reduce((acc, val) => acc + val, 0)
return Math.round(sum / validNumbers.length)
}
const values = ['10', '20.5', 'invalid', '30', null, '40.7']
const average = calculateAverage(values)
console.log(average) // 20 (10 + 20 + 30 + 40 = 100, 100 / 4 = 25, rounded to 20)
Handling Pagination Parameters
typescript
import { toInt } from 'radash'
function parsePaginationParams(params: Record<string, any>) {
return {
page: toInt(params.page, 1),
limit: toInt(params.limit, 10),
offset: toInt(params.offset, 0)
}
}
const params = {
page: '2',
limit: '25.5',
offset: 'invalid'
}
const pagination = parsePaginationParams(params)
console.log(pagination) // { page: 2, limit: 25, offset: 0 }
Handling Game Data
typescript
import { toInt } from 'radash'
function processGameData(data: any) {
return {
level: toInt(data.level, 1),
score: toInt(data.score, 0),
lives: toInt(data.lives, 3),
coins: toInt(data.coins, 0)
}
}
const gameData = {
level: '5.5',
score: '1250.75',
lives: 'invalid',
coins: null
}
const processed = processGameData(gameData)
console.log(processed) // { level: 5, score: 1250, lives: 3, coins: 0 }
Notes
- String Parsing: Only parses the numeric part at the beginning of the string
- Decimals: Truncates the decimal part, does not round
- Invalid Values: Returns the default value for unconvertible values
- Type Safety: Provides complete TypeScript type support
- Performance: Conversion is fast, suitable for frequent use
Differences from Other Methods
parseInt()
: Native method, returns NaN for invalid valuesNumber()
: Converts the entire string, may return NaNtoInt()
: Safe conversion method provided by radash
Practical Application Scenarios
- Form Processing: Safely convert user input
- API Processing: Handle numeric fields that may contain strings
- Database Operations: Handle numbers in query results
- Configuration Parsing: Parse numbers in configuration files
- Data Validation: Validate and convert numeric input