简体   繁体   中英

How to make one digit after decimal point?

Searching how to make two digit after decimal point as below

$ = (double) (((int)($ * 100)) / 100.0);

Anyone can help to how to make "one digit" after decimal point ?

thanks a lot

If you are using doubles to store/calculate currency values, then you will likely find yourself in a world of pain with rounding. Been there, done that, got the scars.

I highly recommend that you use BigDecimal values for ALL currency values, and do not even involve doubles in the instantiation. Always use the String constructor.

See related questions here and here .

What about this:

$ = (double) (((int)($ * 10)) / 10.0);

Note: edited after the comment. If you need java and rounding instead of truncate try this:

import java.lang.Math;

double a;
a = ((double) (round(a*10))) / 10.0;

This will shift left the dot of one position, round to the nearest integer and then shift the dot back to the right one position.

Edited second time:

What you need is still unclear. If you are fine with truncate as before:

double $=1.24*(double)amount;
$ = (double) (((int)($ * 1000)) / 1000.0);
outelc.setText("ELC(1.24)= " + Double.toString($) + " /pc");

If you need rounding:

double $=1.24*(double)amount;
$ = (double) ((round($ * 1000)) / 1000.0);
outelc.setText("ELC(1.24)= " + Double.toString($) + " /pc");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM