Skip to content
Fix Code Error

Using String Format to show decimal up to 2 places or simple integer

March 13, 2021 by Code Error
Posted By: Anonymous

I have got a price field to display which sometimes can be either 100 or 100.99 or 100.9, What I want is to display the price in 2 decimal places only if the decimals are entered for that price , for instance if its 100 so it should only show 100 not 100.00 and if the price is 100.2 it should display 100.20 similarly for 100.22 should be same .
I googled and came across some examples but they didn’t match exactly what i wanted :

// just two decimal places
String.Format("{0:0.00}", 123.4567);      // "123.46"
String.Format("{0:0.00}", 123.4);         // "123.40"
String.Format("{0:0.00}", 123.0);         // "123.00"

Solution

An inelegant way would be:

var my = DoFormat(123.0);

With DoFormat being something like:

public static string DoFormat( double myNumber )
{
    var s = string.Format("{0:0.00}", myNumber);

    if ( s.EndsWith("00") )
    {
        return ((int)myNumber).ToString();
    }
    else
    {
        return s;
    }
}

Not elegant but working for me in similar situations in some projects.

Answered By: Anonymous

Related Articles

  • How can i display data from xml api in flutter?
  • How can I pass a wct test while rearranging children…
  • How can I pass a list as a command-line argument…
  • Checking if a variable is an integer in PHP
  • Python: Float to Decimal conversion and subsequent…
  • How can I format a decimal to always show 2 decimal places?
  • How to update other fields based on a field value in…
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • How to change the color of vaadin-select-text-field…
  • How to print binary tree diagram?
  • No function matches the given name and argument types
  • Regular expression to match numbers with or without…
  • Problems Installing CRA & NextJS from NPM…
  • Reference - What does this regex mean?
  • regex match any single character (one character only)
  • How to display pandas DataFrame of floats using a…
  • Polymer 1.0 'array-style' path accessors,…
  • Remove trailing zeros from decimal in SQL Server
  • Can't install via pip because of egg_info error
  • Fastest way to iterate over all the chars in a String
  • Pandas: convert column (price data) to integer
  • Django - update inline formset not updating
  • Vue + VUEX + Typescript + Vue Router. component not…
  • How to fix overlapping issue in the Qweb reports?
  • How to use html template with vue.js
  • What are the undocumented features and limitations…
  • Text Progress Bar in the Console
  • Component Inheritance with vue js
  • Getting the closest string match
  • How to import XML file into MySQL database table…
  • Smart way to truncate long strings
  • Difference between
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Ember 2, filter relationship models (hasMany,…
  • What is the difference between re.search and re.match?
  • How to prevent scrolling the whole page?
  • Regex on htaccess file gives INTERNAL REDIRECT error
  • Which is more efficient, a for-each loop, or an iterator?
  • Correct way to convert size in bytes to KB, MB, GB…
  • Explanation on Integer.MAX_VALUE and…
  • Why does C++ code for testing the Collatz conjecture…
  • SQL query return data from multiple tables
  • How to truncate float values?
  • The definitive guide to form-based website authentication
  • Change column type in pandas
  • multiple login routes using ember-cli-simple-auth
  • vaadin combobox load wrong custom style
  • Unexpected end of JSON input while parsing
  • how to determine which bar was clicked on a chart js
  • Difference between decimal, float and double in .NET?
  • How does PHP 'foreach' actually work?
  • Limiting double to 3 decimal places
  • Javascript if statement inside return
  • Solidity ParserError: Expected ';' but got 'is'
  • Avoid trailing zeroes in printf()
  • How to check if a string contains text from an array…
  • Javascript array to JSON array
  • Align input points with multiple variable lengths
  • Vue price range filter
  • Firestore, Security Rules, how to limit a size of…
  • How can I set hours and minutes of date with oracle sql?
  • Backbone.Marionette - Collection within…
  • Checkout another branch when there are uncommitted…
  • Design DFA accepting binary strings divisible by a…
  • Preventing orphaned words but exclude tag
  • XMLHttpRequest cannot load ✘✘✘ No…
  • How to validate decimal value in vee validate 3.0 version
  • Float vs Decimal in ActiveRecord
  • Vuejs: Show error messages as popups
  • What is an optional value in Swift?
  • How to add mixin for height in mwc textfield?
  • Examples of GoF Design Patterns in Java's core libraries
  • Add Keypair to existing EC2 instance
  • Pyparsing: Parse Dictionary-Like Structure into an…
  • How do I parse a string in Python and obtain…
  • What is a NullReferenceException, and how do I fix it?
  • Parsing Nested Polymorphic Objects with GSON and Retrofit
  • Identifying and solving…
  • Converting a value to 2 decimal places within jQuery
  • How Spring Security Filter Chain works
  • My DIV elements go diagonal instead of horizontal
  • Flex: REJECT rejects one character at a time?
  • How do I limit the number of digits from 6 to 4 in…
  • I can't understand why this JAXB…
  • How to create websockets server in PHP
  • Replace/Update The Existing Array of Object that…
  • Logging best practices
  • What is your most productive shortcut with Vim?
  • What's the best practice to round a float to 2 decimals?
  • ExpressJS How to structure an application?
  • Any workaround to TimeSpan.ParseExact with more than…
  • Need a flexible currency filter in VueJS
  • Validate that a string is a positive integer
  • Change private static final field using Java reflection
  • EL access a map value by Integer key
  • Detect whether a Python string is a number or a letter
  • coercing to Unicode: need string or buffer, NoneType…
  • Display number always with 2 decimal places in
  • I want to create a SQLite database like in the…
  • How do Mockito matchers work?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

python exception message capturing

Next Post:

How to set time delay in javascript

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error