Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update feature NumberToWords #31

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 3 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,28 +89,16 @@ words.convertWordsToNumberString(); // '3212' as String
- #### Converting Persian numbers to word - [source](https://github.com/persian-tools/dart-persian-tools/blob/master/lib/src/core/number_to_words/number_to_words.dart)

```dart
final stringDigit = '257,433';
final intDigit = -128;

/// use [numberToWordsString] method to convert [stringDigit] to persian

numberToWordsString(stringDigit); // 'دویست و پنجاه و هفت هزار و چهارصد و سی و سه'

/// [numberToWordsString] also has an optional parameter
/// by default [ordinal] is [false], [true] makes the output an ordinal word

numberToWordsString(stringDigit, ordinal: true); // 'دویست و پنجاه و هفت هزار و چهارصد و سی و سوم'

/// use [numberToWordsInt] method to convert [intDigit] to persian
/// use [numberToWords] method to convert [intDigit] to persian
numberToWords(intDigit); // 'منفی صد و بیست و هشت'

/// [numberToWordsInt] also has an optional parameter
/// [numberToWords] also has an optional parameter
/// by default [ordinal] is [false], [true] makes the output an ordinal word
numberToWords(intDigit, ordinal: true); // 'منفی صد و بیست و هشتم'

/// you can simply use extension methods on int or String objects
stringDigit.convertNumToWords(); // 'دویست و پنجاه و هفت هزار و چهارصد و سی و سه'

/// you can simply use extension methods on int objects
intDigit.convertNumToWords(); // 'منفی صد و بیست و هشت'
```

Expand Down
17 changes: 2 additions & 15 deletions example/example_number_to_words.dart
Original file line number Diff line number Diff line change
@@ -1,28 +1,15 @@
import 'package:persian_tools/persian_tools.dart';

void main() {
final stringDigit = '257,433';
final intDigit = -128;

/// use [numberToWordsString] method to convert [stringDigit] to persian
print(numberToWordsString(
stringDigit)); // 'دویست و پنجاه و هفت هزار و چهارصد و سی و سه'

/// [numberToWordsString] also has an optional parameter
/// by default [ordinal] is [false], [true] makes the output an ordinal word
print(numberToWordsString(stringDigit,
ordinal: true)); // 'دویست و پنجاه و هفت هزار و چهارصد و سی و سوم'

/// use [numberToWordsInt] method to convert [intDigit] to persian
/// use [numberToWords] method to convert [intDigit] to persian
print(numberToWords(intDigit)); // 'منفی صد و بیست و هشت'

/// [numberToWordsInt] also has an optional parameter
/// [numberToWords] also has an optional parameter
/// by default [ordinal] is [false], [true] makes the output an ordinal word
print(numberToWords(intDigit, ordinal: true)); // 'منفی صد و بیست و هشتم'

/// you can simply use extension methods on int or String objects
print(stringDigit
.convertNumToWords()); // 'دویست و پنجاه و هفت هزار و چهارصد و سی و سه'

print(intDigit.convertNumToWords()); // 'منفی صد و بیست و هشت'
}
13 changes: 8 additions & 5 deletions lib/src/constants/number_to_words/constants.dart
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
const base = 1000;
const errorMessage =
'PersianTools: numberToWords - the number must be a safe integer less than 16 digits';

const zeroFa = 'صفر';

const endsWithAnd = ' و ';

const scale = ['', 'هزار', 'میلیون', 'میلیارد'];
const andFa = ' و ';

const numberToWord = {
0: '',
1: 'یک',
2: 'دو',
3: 'سه',
Expand Down Expand Up @@ -44,4 +42,9 @@ const numberToWord = {
700: 'هفتصد',
800: 'هشتصد',
900: 'نهصد',
1000: 'هزار',
1000000: 'میلیون',
1000000000: 'میلیارد',
1000000000000: 'تریلیون',
1000000000000000: 'کوآدریلیون',
};
123 changes: 65 additions & 58 deletions lib/src/core/number_to_words/number_to_words.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,81 +2,88 @@ import 'package:persian_tools/persian_tools.dart';
import 'package:persian_tools/src/constants/number_to_words/constants.dart';
import 'package:persian_tools/src/internal_methods.dart';

/// Gets an [int] with 3 or less digits as input and converts it to persian
String _numToWord(int number) {
var unit = 100;
var result = '';

while (unit > 0) {
if ((number / unit).floor() * unit != 0) {
if (numberToWord.containsKey(number)) {
result += numberToWord[number]!;
break;
} else {
result += '${numberToWord[(number / unit).floor() * unit]} و ';
number %= unit;
}
}
unit = (unit / 10).floor();
}
return result;
/// Gets an [int] as input and checks if it's a negative number
bool _isNegative(int number) {
return number < 0;
}

/// Checks current [input] for negative [value] and deploying converting process
String _convert(int number, bool ordinal) {
var result = <String>[];

final isNegative = number < 0;
number = isNegative ? number * -1 : number;

while (number > 0) {
result.add(_numToWord(number % base));
number = (number / base).floor();
}
if (result.length > 4) return '';

for (var i = 0; i < result.length; i++) {
if (result[i] != '' && i != 0) result[i] += ' ${scale[i]} و ';
}
result = result.reversed.toList();

var words = result.join('');

if (words.endsWith(endsWithAnd)) {
words = words.substring(0, (words.length - 3));
}
/// Returns error message for [input] with more than 16 digits
String _numberIsNotValidError() {
return errorMessage;
}

words = trim(isNegative ? 'منفی $words' : words);
/// Gets an [int] as input and if exists, returns persian word
String _getWord(int number) {
return numberToWord[number] ?? '';
}

if (ordinal) words = addOrdinalSuffix(words);
/// Gets an [String] input and add negative persian prefix to it
String _addNegativeSuffix(String number) {
return 'منفی $number';
}

return words;
/// Gets an [int] as input and returns [unitName] for numbers over 1000
/// [_getUnitName] parameter is calculated by subtracting current [map] key
/// from [separated] length multiplied by 3
String _getUnitName(int numberOfZeros) {
return numberOfZeros == 0
? ''
: numberToWord[int.parse('1${"0" * numberOfZeros}')]!;
}

/// Returns Persian word of the given number in String. Number can contain commas.
/// You can determine returned string has ordinal suffix or not by `ordinal` flag.
String? numberToWordsString(String number, {bool ordinal = false}) {
if (number.isEmpty) return null;
if (number == '0') return zeroFa;
/// Gets an [int] with 3 or less digits as input and converts it to persian
/// [num] between 1 & 19,except for 10, are converted directly like other
/// numbers that divisible by 10
/// For other numbers, the remainder of dividing by 10 would be passed to
/// [_transformToWord]
String _transformToWord(int number) {
if (number == 0) return '';
if (number <= 19 && number != 10) return _getWord(number);

final residual = number <= 99 ? number % 10 : number % 100;
return residual == 0
? _getWord(number)
: '${_getWord(number - residual)} و ${_transformToWord(residual)}';
}

return _convert(removeCommas(number).toInt(), ordinal);
/// Transform [input] to string, breaks the number into three digit
/// parts, assign the string to [separated], get each part's [unitName]
/// and [transformedVal] inside [map] function of [numberArr]. each separated
/// part is handled in [map]. After [map] function, [where] function checks
/// the result created by [map] and ignores the empty items.
/// Finally [toList] combines and returns the result of the parts as a [String]
String _performer(int number) {
if (number <= 999) return _transformToWord(number);
final separated = addCommas(number.toString()).split(',');
final numberArr = separated
.asMap()
.entries
.map((e) {
final transformedVal = _transformToWord(int.parse(e.value, radix: 10));
final unitName = _getUnitName((separated.length - (e.key + 1)) * 3);
return transformedVal.isNotEmpty ? '$transformedVal $unitName' : '';
})
.where((element) => element.length > 1)
.toList();
return trim(numberArr.join(andFa));
}

/// Returns Persian word of the given number in int You can determine
/// returned string has ordinal suffix or not by `ordinal` flag.
/// The current [input] is passed to [_performer] as positive integer
/// If [input] is negative, prefix would be added to [_performer] result
/// If `ordinal` is true, suffix would be added to the result of [tmpResult]
String numberToWords(int number, {bool ordinal = false}) {
if (number == 0) return zeroFa;
return _convert(number, ordinal);
}

/// [String] Extension wrapper to convert number to Persian word on String object
extension NumberToPersianWordsString on String {
String? convertNumToWords({bool ordinal = false}) =>
numberToWordsString(this, ordinal: ordinal);
if (number.toString().length > 16) return _numberIsNotValidError();
final _tmpResult = _isNegative(number)
? _addNegativeSuffix(_performer(number.abs()))
: _performer(number);
return ordinal ? addOrdinalSuffix(_tmpResult) : _tmpResult;
}

/// [int] Extension wrapper to convert number to Persian word on int object
extension NumberToPersianWordsInt on int {
String? convertNumToWords({bool ordinal = false}) =>
String convertNumToWords({bool ordinal = false}) =>
numberToWords(this, ordinal: ordinal);
}
Loading