Skip to content

decimalsOnly() Helper Method

The decimalsOnly() Helper Method module provides a helper function that converts the first argument into a string and then tests it for digit and dot characters. If the test passes, then the digits/dot are returned, and otherwise the second argument is returned (which should be the original number).

This helper function is essentially a function tailored specifically for decimal number counter UI validation.

Import

To import the decimalsOnly() Helper Method:

javascript
import { decimalsOnly } from '@obewds/vueventus'

Arguments

Returns: Number

ArgsTypeStatusDescription
valueNumber or StringRequiredThe string or number to process
originalNumberNumberRequiredA fallback number if the 1st argument value has no positive integer characters

Use Examples

javascript
const startNumber = 10

console.log( decimalsOnly(11, startNumber) )
// returns (number): 11

console.log( decimalsOnly(9, startNumber) )
// returns (number): 9

console.log( decimalsOnly(11.123, startNumber) )
// returns (number): 11.123

console.log( decimalsOnly('11.123', startNumber) )
// returns (number): 11.123

console.log( decimalsOnly('abc', startNumber) )
// returns (number): 10

Module Code

ts
// ./src/helpers/decimalsOnly.ts

export default function (value: number|string, originalNumber: number): number {

    const val = (String(value)).trim()

    // Allow only number and dot characters
    if (/^[0-9]*\.?[0-9]*$/.test(val)) {

        return Number(val)
        
    } else {

        return originalNumber

    }

}

Released under the MIT License