c# - Get decimals of a double? -
i have function adds double double need add digits after decimal point , number of digits varies based on size of number.
public double calculate(double x, double add) { string xstr; if (x >= 10) xstr = x.tostring("00.0000", numberformatinfo.invariantinfo); if (x >= 100) xstr = x.tostring("000.000", numberformatinfo.invariantinfo); if (x < 10) xstr = x.tostring("0.00000", numberformatinfo.invariantinfo); string decimals = xstr.remove(0, xstr.indexof(".") + 1); decimals = (convert.todouble(decimals) + add).tostring(); xstr = xstr.substring(0, xstr.indexof(".") + 1) + decimals; x = convert.todouble(xstr, numberformatinfo.invariantinfo); return x; }
i'm wondering if there isn't simpler way without having convert number string first , adding decimal part of it. can see number added should 6 digit number ever decimal separator is.
if take remainder of object divided 1
you'll fractional portion of number:
double remainder = somedouble % 1;
to write whole method out, it's simple as:
public double calculate(double x, double add) { return math.floor(x) + (x + add) % 1; }
(this 1 of times you're glad %
computes remainder, rather modulus. work negative numbers well.)
Comments
Post a Comment