c# - How can I strip zeros and decimal points off of decimal strings? -
the following code outputs:
12.1 12.100 12.1000 12.00 12 12.0000
how can change outputs:
12.1 12.1 12.1 12 12 12
math.round seems thing, makes me define how many decimal places want, want them variable above.
if there no mathematical way it, i'll strip zeros , decimal points off right side of strings, think there math way handle this.
using system; using system.collections.generic; namespace test8834234 { public class program { static void main(string[] args) { list<string> decimalsasstrings = new list<string> { "12.1", "12.100", "12.1000", "12.00", "12", "12.0000" }; foreach (var decimalasstring in decimalsasstrings) { decimal dec = decimal.parse(decimalasstring); console.writeline(dec); } console.readline(); } } }
you can use decimal's tostring parameter:
string s = dec.tostring("0.#");
note: may have internationalization issue code. way have coded it, use culture info user's computer, may have other .
decimal separator. might cause program give incorrect results users have .
thousands separator.
if want guarantee parse method behave same, use cultureinfo.invariantculture. if want parse string according user's culture settings, doing fine.
Comments
Post a Comment