How do you format a string in python to given precision?
Question: I need to return a string in a program, which is finding value of e to nth
precision. I tried doing `'%f' % (n,e)`. Please suggest the right syntax.


Answer: You can manually set the precision by importing `decimal` module.

Here's the code:

    
    
    from decimal import *
    getcontext().prec = 40     # Decimal precision you require
    value = Decimal(1).exp()
    string_value = str(value)    # Convert to string
    

Here's the working example:

    
    
    >>> from decimal import *
    >>> getcontext().prec = 40
    >>> Decimal(1).exp()
    Decimal('2.718281828459045235360287471352662497757')
    >>> data = Decimal(1).exp()
    >>> str(data)
    '2.718281828459045235360287471352662497757'
    >>> 
    

Here's for 2000 decimal places:

    
    
    >>> from decimal import *
    >>> getcontext().prec = 2000
    >>> value = Decimal(1).exp()
    >>> str(value)
    '2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274274663919320030599218174135966290435729003342952605956307381323286279434907632338298807531952510190115738341879307021540891499348841675092447614606680822648001684774118537423454424371075390777449920695517027618386062613313845830007520449338265602976067371132007093287091274437470472306969772093101416928368190255151086574637721112523897844250569536967707854499699679468644549059879316368892300987931277361782154249992295763514822082698951936680331825288693984964651058209392398294887933203625094431173012381970684161403970198376793206832823764648042953118023287825098194558153017567173613320698112509961818815930416903515988885193458072738667385894228792284998920868058257492796104841984443634632449684875602336248270419786232090021609902353043699418491463140934317381436405462531520961836908887070167683964243781405927145635490613031072085103837505101157477041718986106873969655212671546889570350354021234078498193343210681701210056278802351930332247450158539047304199577770935036604169973297250886876966403555707162268447162560798826517871341951246652010305921236677194325278675398558944896970964097545918569563802363701621120477427228364896134225164450781824423529486363721417402388934412479635743702637552944483379980161254922785092577825620926226483262779333865664816277251640191059004916449982893150566047258027786318641551956532442586982946959308019152987211725563475463964479101459040905862984967912874068705048958586717479854667757573205681288459205413340539220001137863009455606881667400169842055804033637953764520304024322566135278369511778838638744396625322498506549958862342818997077332761717839280349465014345588970719425863987727547109629537415211151368350627526023264847287039207643100595841166120545297030236472549296669381151373227536450988890313602057248176585118063036442812314965507047510254465011727211555194866850800368532281831521960037356252794495158284188294787610852639814'
    >>> 
    

Hope this helps.

