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

added fraction decimal to binary #251

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
60 changes: 60 additions & 0 deletions conversions/fraction_decimal_to_binary.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// Author: ShivangSrivastava
// Email: [email protected]

/// Converts a decimal number to binary with optional precision for fractional part
/// https://www.geeksforgeeks.org/convert-decimal-fraction-binary-number/
String decimalToBinary(double value, [int precision = 10]) {
bool isNegative = value.isNegative;
if (isNegative) {
value = -value;
}

int intPart = value.toInt();
String binaryOfIntPart = intToBinary(intPart);

double fracPart = value - intPart;
String binaryOfFracPart = fracToBinary(fracPart, precision);

return isNegative
? "-$binaryOfIntPart.$binaryOfFracPart"
: "$binaryOfIntPart.$binaryOfFracPart";
}

/// Converts an integer to binary string
String intToBinary(int value) {
String binary = "";

while (value > 0) {
binary = (value % 2).toString() + binary;
value = value ~/ 2;
}

return binary;
}

/// Converts a fractional part to binary string up to given precision
String fracToBinary(double value, [int precision = 10]) {
StringBuffer binary = StringBuffer();
double fraction = value;

for (int i = 0; i < precision; i++) {
fraction *= 2;
if (fraction >= 1) {
binary.write('1');
fraction -= 1;
} else {
binary.write('0');
}

if (fraction == 0) {
break;
}
}

return binary.toString();
}

void main() {
String result = decimalToBinary(10.25);
print(result);
}